Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Increment Object set javascript

I have an object set

var obj = {
 ref01:{
 test:"abc"
},
ref02:{
 test:"xyz"
},
ref03:{
 test:"pqr"
}
}

and I have new object

const test = {
  test:"def"
}

I want to update the object above with increment value of ref Now ref is03 , I want to append like ref04 and increment each time based on existing obj.

var obj = {
 ref01:{
 test:"abc"
},
ref02:{
 test:"xyz"
},
ref03:{
 test:"pqr"
},
ref04:{
 test:"def"
}
}

i tried object.assign but its directly passing the value . obj = object.assign(obj,{ref:test})

So how can i get it ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you want a list: i.e.

const obj = {
    testObjects: [
        {
            test: 'abc'
        },
        ...
    ]
}

then you can just run:

obj.testObjects.push({test: 'xyz'});

OR if this is an API response you can't change the schema of:

//find last index so you can add the ref obj
const getFormattedIndex = (idx) => String(idx).padStart(2, '0');
let i = 1;
while(obj[`ref${getFormattedIndex(i)}`]) {
   i++;
}
//add object with the correct sequential key
obj[`ref${getFormattedIndex(i)}`] = {test: 'xyz'};

or you could be a bad person and use scope-bleed with a ghetto for loop 😇:

//find last index so you can add the ref obj
const getFormattedIndex = (idx) => String(idx).padStart(2, '0');
for (var i = 1; obj[`ref${getFormattedIndex(i)}`]; i++);
//add object with the correct sequential key
obj[`ref${getFormattedIndex(i)}`] = {test: 'xyz'};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda