【发布时间】:2021-10-19 16:59:29
【问题描述】:
如果克隆对象发生变化,原始对象也会发生变化
const original = {
"appList": [{
"appId": "app-1",
"serviceList": [{
"service": "service-1",
"mList": ["somedata"]
},{
"service": "service-2",
"mList": []
},{
"service": "service-3",
"mList": []
}]
}]
}
const clone = Object.assign({}, original);
尝试做以下改变
clone.appList = clone.appList.filter(app => app.appId == 'app-1').map( app => {
let serviceList = [...app.serviceList];
if(app.serviceList && app.serviceList.length) {
app.serviceList = serviceList.filter(service => {
const { mList } = service;
return mList && mList.length;
});
}
return app;
}
);
当记录原始对象时也改变了
console.log(clone);
console.log(original);
【问题讨论】:
-
clone不是深拷贝,只是浅拷贝。 -
因为这是浅拷贝,没有深拷贝。
Object.assign只创建一个具有第一层对象属性的新对象。深度复制对象并非易事。简单对象最简单的方法是使用 JSON。 Stringyfy 和解析。查看网络和 StackOverflow。因为这个话题并不新鲜。使用deep copy object等关键字进行搜索。 -
您永远不会创建
app对象的副本,您只能通过为每个对象分配一个新的.serviceList来改变它们。 -
const clone = JSON.parse(JSON.stringify(object));你试过了吗?
标签: javascript arrays object ecmascript-6 ecmascript-5