我在上面的例子中复制了我的代码,我的期望是得到一个操作:
[{"data":[{"val":1}]},{"data":[{"val":2}]}]
但我的结果是
[{"data":[{"val":2}]},{"data":[{"val":2}]}]
我不明白为什么请帮助我深入了解这个问题
答案 0 :(得分:1)
不确定你想要在那里实现什么,但根据序列,你需要在push
时复制对象:
_.forEach([{a:1},{a:2}],function(acombination){
console.log("acombination",acombination);
_.find([1,2], function(aheader, headerindex) {
/*Only for repeat the value*/
if (aheader == 1) {
for (let i = 0; i < 2; i++) {
clonedData.data[headerindex].val = acombination.a;
}
}
});
var newObj = {};
newObj = clonedData;
dataObj.push(JSON.parse(JSON.stringify(newObj)));
// I stringified and parsed to create a new copy. You were pushing the object and later changing the same object, which changed both the values.
});
console.log("Ss",JSON.stringify(dataObj))
答案 1 :(得分:1)
对这个问题有点不确定,但你可以尝试深度克隆&#34; clonedData&#34;在推入dataObj数组之前应该解决输出问题。我认为JS是通过引用分配的。
而不是
var newObj = {};
newObj = clonedData;
dataObj.push(newObj);
使用
var newObj = JSON.parse(JSON.stringify(clonedData));
dataObj.push(newObj);