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

103
Visualizações
Push in typescript is appending the last modified object in a loop

I am trying to create an array out of a modified object but the Array<any>.push() method always appends the object that gets modified at the end of the loop. Here is sample code that I am trying to work with:

let data: any = JSON.parse('{"messages":[{"id":"1234"},{"id":"2345"},{"id":"3456"}]}');
let myObject:any;
let idMapping: any[] = [];
for(let index = 0; index < 1; index++) {
    myObject = {DocID: "", index: index};
    for (let val of data.messages) {
        myObject.DocID = val.id;
        // console.log("After update: ", myObject); // this gives me the correct object
        idMapping.push(myObject);
    }
}
console.log(idMapping) // array with same identical values, infact the last modified value in for loop

This is giving me a list of same objects against what I expected it to be a list of objects having different DocID.

I am new to typescript and Nodejs, so any help would be appreciated.

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

0

You modify and add the same object to the array over and over again!

Instead you should create a new object every iteration:

let data: any = JSON.parse('{"messages":[{"id":"1234"},{"id":"2345"},{"id":"3456"}]}');
let idMapping: any[] = [];
for(let index = 0; index < 1; index++) {
   
    for (let val of data.messages) {
       let myObject = {DocID: "", index: index};
        myObject.DocID = val.id;
        // console.log("After update: ", myObject); // this gives me the correct object
        idMapping.push(myObject);
    }
}
console.log(idMapping)
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