【发布时间】:2021-12-05 09:40:10
【问题描述】:
我试图从修改后的对象中创建一个数组,但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 的新手,因此我们将不胜感激。
【问题讨论】:
标签: javascript node.js arrays typescript