我有一个父数组,我正在从父数组中获取一个经过过滤的数组(子数组)。在更改子数组时,我的父数组也在更改。请您帮我如何保持相同的父数组不变。< / p>
SELECT
答案 0 :(得分:1)
filter()
不会复制对象。它只是为您提供了一个新数组,其中引用了parentArray
中完全相同的对象。
如果要在childArray
中进行复印,则需要自己完成。一种实现方法是将map()
与Object.assign()
一起使用,这将为您的对象创建浅表副本:
let parentArray=[
{ "id":"1", "Package":"Tes1", "Version":"20080210-1.1", "Maintainer":"Stefano Canepa"},
{ "id":"1", "Package":"Test2", "Version":"7.0-1", "Maintainer":"Debian Games Team"},
{ "id":"1", "Package":"Test3", "Version":"20080210-1.1", "Maintainer":"Stefano Canepa"},
{ "id":"1", "Package":"Test4", "Version":"7.0-1", "Maintainer":"Debian Games Team"},
{ "id":"5", "Package":"Tdst5", "Version":"20080210-1.1", "Maintainer":"Stefano Canepa"},
{ "id":"6", "Package":"Test6", "Version":"7.0-1", "Maintainer":"Debian Games Team"},
{ "id":"7", "Package":"Test7", "Version":"20080210-1.1", "Maintainer":"Stefano Canepa"},
{ "id":"8", "Package":"Test8", "Version":"7.0-1", "Maintainer":"Debian Games Team"}
];
let childArray=parentArray.filter(x=>x.id=="1")
.map(obj => Object.assign({}, obj)) // make copies
console.log("before"+JSON.stringify(parentArray));
childArray.forEach(value=>value.Package="changed")
console.log("after"+JSON.stringify(parentArray));