gpt4 book ai didi

JavaScript深度嵌套数组v的浅数组拼接

转载 作者:行者123 更新时间:2023-12-02 15:21:11 25 4
gpt4 key购买 nike

我有一个对象数组,其中又包含对象数组。我希望过滤“顶级”(浅层)数组和“嵌套”数组。为了维护一个确定的数组,我循环访问了remoteData,并将每个对象推送到definitiveArray 和filteredArr 中。我的想法是我只操作filteredArray。

如果我使用filteredArray.spice(0, 1)循环并从filteredArray的浅数组中拼接一个项目,它只会影响filteredArray,即我正在尝试操作的那个。然而,如果我尝试使用filteredArray[0].Colours.splice(0, 1)从filteredArray.nested数组中拼接一个项目,它会从filteredArray和definitiveArray中删除该项目。

我猜测这是由于我对 JavaScript 引用的工作方式的误解所致。如果能提供有关如何克服此问题的解释和指导,我们将不胜感激。

这里有一个 plnkr http://plnkr.co/edit/MKSlTogO3YkzHuKnHmwH

remoteData = [
{ Id: 1, Text: 'Item 1', Colours: [ { Id: 1, Colour: 'Red' }, { Id: 2, Colour: 'Orange' } ] },
{ Id: 2, Text: 'Item 2', Colours: [ { Id: 1, Colour: 'Yellow' }, { Id: 2, Colour: 'Green' } ] },
{ Id: 3, Text: 'Item 3', Colours: [ { Id: 1, Colour: 'Blue' }, { Id: 2, Colour: 'Indigo' } ] },
{ Id: 4, Text: 'Item 4', Colours: [ { Id: 1, Colour: 'Violet' }, { Id: 2, Colour: 'Red' } ] },
{ Id: 5, Text: 'Item 5', Colours: [ { Id: 1, Colour: 'Orange' }, { Id: 2, Colour: 'Yellow' } ] },],
definitiveArray = [],
filteredArray = [];

/*
* splicing an item out of the deeply nested array affects both
*/
len = remoteData.length;
for (var i = 0; i < len; i++) {
//push data into both the definitive array and the filter array
definitiveArray.push(remoteData[i]);
filteredArray.push(remoteData[i]);
}
console.log(filteredArray[0].Colours.length); //obviously 2
console.log(definitiveArray[0].Colours.length); //obviously 2

//splice the first item in the first Colours array for ONLY the filteredArray
filteredArray[0].Colours.splice(0, 1);
console.log(filteredArray[0].Colours.length); //obviously 1
console.log(definitiveArray[0].Colours.length); //also 1 rather than 2 that I expected


/*
* If however I splice an item out of the shallow array, it affects only the filteredArray
*/
console.log(filteredArray.length); //obviously 5
console.log(definitiveArray.length); //obviously 5

//remove the first item in ONLY the filteredArray
filteredArray.splice(0, 1);

console.log(filteredArray.length); //obviously 4
console.log(definitiveArray.length); //still 5 as this array has been left unaffected

这里

最佳答案

您需要为每个嵌套数组创建一个新实例。

这是一个简单的方法 -

for (var i = 0; i < len; i++) {
//push data into both the definitive array and the filter array
definitiveArray.push(JSON.parse(JSON.stringify(remoteData[i])));
filteredArray.push(JSON.parse(JSON.stringify(remoteData[i])));
}

关于JavaScript深度嵌套数组v的浅数组拼接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com