原始数组是newData
。我想为newData添加一个数组元素,添加的数组元素应该有Rank 1
。
问题是两个记录的Rank都会更新为1。第二记录的等级应为1,第一记录的等级应为null
请告诉我这里我做错了什么。
let newData = [{
"key1": {
"cc":'IND'
},
"key2": {
"rank": null
}
}];
let setData = newData.concat(newData.slice());
setData.forEach(data => {
data.key2.rank =+ 1;
});
答案 0 :(得分: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);
答案 1 :(得分:0)
setData.forEach(data => {
data.key2.rank += 1;
});
尝试将您的运营商从=+
转换为+=
而不是