typescript中的 Push在循环中追加最后修改的对象



我试图从修改的对象中创建一个数组,但Array<any>.push()方法总是附加在循环结束时修改的对象。以下是我试图使用的示例代码:

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

这给了我一个相同对象的列表,而不是我期望的具有不同DocID的对象列表。

我是typescript和Nodejs的新手,所以任何帮助都会很感激。

你修改和添加相同的对象到数组一遍又一遍!

应该在每次迭代中创建一个新对象:

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)

最新更新