原始数组是newData
。我想向 newData 添加一个数组元素,并且添加的数组元素应具有 Rank 1
。
问题是两条记录的排名都更新为 1。第二条记录的排名应为 1,第一条记录的排名应为 null
请告诉我我在这里做错了什么。
let newData = [{
"key1": {
"cc":'IND'
},
"key2": {
"rank": null
}
}];
let setData = newData.concat(newData.slice());
setData.forEach(data => {
data.key2.rank =+ 1;
});
最佳答案
您可以尝试以下操作
let newData = [{"key1": {"cc":'IND' }, "key2": {"rank": null}}];
// Concatenate arrays use spread operator and can use map rather than slice
let setData = [...newData, ...newData.map(data => {
/* Objects are passed by reference, you need to break the reference
* to create the clone of the object. */
data = JSON.parse(JSON.stringify(data));
data.key2.rank =+ 1;
return data;
})];
console.log(setData);
关于javascript - 复制数组元素修改并再次添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50485118/