Home > Software engineering >  Push in typescript is appending the last modified object in a loop
Push in typescript is appending the last modified object in a loop

Time:10-19

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.

CodePudding user response:

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)
  • Related