gpt4 book ai didi

javascript - 过滤器不适用于第三个子级别(嵌套级别)

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

我正在尝试过滤嵌套级别为 3 的数组。我必须在最后一级过滤此数组。

array = [{
children: [{
children: [{
children: [],
id: 2694,
name: "Some Random data"
}, {
children: [],
id: 2695,
name: "Another Random Data"
}],
id: 2574,
name: "Test data",
}],
id: 2530,
name: "Main Test data"
}, {
children: [{
children: [{
children: [],
id: 2696,
name: "Secondary test Data"
}, {
children: [],
id: -1,
name: "Random Text"
}],
id: 2575,
name: "Another random Text"
}],
id: 2531,
name: "New Data"
}]

我试过这个功能

function(random){

let array3=[];
this.array.forEach(cap=>{
let tempparent={...cap};
let child1= tempparent.children.forEach(ch=>{
let tempfeat={...ch};
let tempchildren = tempfeat.children.filter(fe=>{
if(fe.id!=random.id){
return fe
}
});
// console.log(tempchildren)
tempfeat.children = tempchildren;
// console.log(tempfeat.children)
});
console.log(child1)
tempparent.children= child1;
console.log(tempparent.children)
nodes3.push(tempparent)
})
this.array= array3
console.log(this.array);
}

我想使用 id 值在第三级过滤它。当 id 匹配时,必须删除匹配的对象。

最佳答案

您可以采用动态方法,将 child 从对象中取出,检查 id,如果找到,则忽略该对象。

否则带 child 并通过递归调用获得一个子集并重建一个新对象并将其推送到结果集中。

这种方法不会改变原始数据,但会返回所有新对象并适用于任意数量的级别。

function remove(array, id) {
return array.reduce((r, { children, ...o }) => {
if (o.id === id) return r;
children = remove(children || [], id);
if (children.length) o.children = children;
r.push(o);
return r;
}, []);
}

var data = [{ children: [{ children: [{ children: [], id: 2694, name: "Some Random data" }, { children: [], id: 2695, name: "Another Random Data" }], id: 2574, name: "Test data", }], id: 2530, name: "Main Test data" }, { children: [{ children: [{ children: [], id: 2696, name: "Secondary test Data" }, { children: [], id: -1, name: "Random Text" }], id: 2575, name: "Another random Text" }], id: 2531, name: "New Data" }],
result = remove(data, 2574);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 过滤器不适用于第三个子级别(嵌套级别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57069971/

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