我有这个对象
complete: true
我想将第一项更改为var newObj = Object.assign({}, originalObj, {
['shop']: [
{...originalObj['shop'][0]
complete: true}, ...originalObj['shop']
]
})
newObj
这个问题是{{1}}最终会有三个对象,我试图编辑的对象会被复制。
答案 0 :(得分:1)
深层复制可能会在某个时候出现问题。当被分配的属性是对象时,Object.assign()复制属性引用。最好使用以下方法。
var originalObj = {
shop: [
{ id: 1, list: "buy milk", complete: false},
{ id: 2, list: "buy bread", complete: false}
]
};
var newObj = JSON.parse(JSON.stringify(originalObj));
newObj.shop[0].complete = true;
答案 1 :(得分:0)
我的评论:“这是因为您在添加此对象后添加整个商店阵列{... originalObj.shop [0],complete:true}”
... originalObj.shop正在传播整个阵列。 所以你有这个
[{the newly edited object with complete = true}, ...originalObj.shop]
...originalObj.shop looks like this :
[{ id: 1, list: "buy milk", complete: false},
{ id: 2, list: "buy bread", complete: false}]
在我的回答中,我过滤了“old”{id:1,list:“buy milk”,完成:false} out。
var changeObject = function(index, objectToEdit){
var newObject = {};
newObject = Object.assign({}, originalObj.shop[index]);
newObject.complete = true;
return newObject;
};
var originalObj = {
shop: [
{ id: 1, list: "buy milk", complete: false},
{ id: 2, list: "buy bread", complete: false}
]
};
var changedObj = changeObject(0, originalObj);
var unchangedObjs = originalObj.shop.filter( sobj => {
if(sobj.id != changedObj.id)
return sobj;
});
var newObj = {
'shop': [
changedObj,
...unchangedObjs
]
};
console.log(JSON.stringify(newObj));
注意到我的回答完全避免了你想要的解决方案。 所以这是你想要的解决方案:
var newObj = {
'shop': [
{...originalObj.shop[0], complete:true},
...originalObj.shop.filter(so => {return so.id != originalObj.shop[0].id})
]
};