[英]Recursively filter an array of infinitely nested objects by mutliple matching conditions but only return parent that has an instance of both matches
[英]Filter array of infinitely nested objects
假设我有一个嵌套对象数组,例如:
const data = [
{
id: 1,
children:[
{
id: 2,
children:[
{
id: 3,
children:[
{
id: 4,
children: [],
},
{
id: 5,
children: [],
}
],
},
],
},
],
},
{
id: 8,
children:[
{
id: 9,
children:[
{
id: 10,
children:[],
},
],
},
],
},
];
我想返回一个新的数组,其中 id: 3 被排除在外。 所以它会变成:
const data = [
{
id: 1,
children:[
{
id: 2,
children:[],
},
],
},
{
id: 8,
children:[
{
id: 9,
children:[
{
id: 10,
children:[],
},
],
},
],
},
];
排除的 id 可以来自任何级别,并且应该删除它及其子级。 这样做的最佳方法是什么? 到目前为止,我已经尝试了其他几种解决方案,但都没有运气。
您可以使用递归和Array.reduce
,..
例如。
const data=[{id:1,children:[{id:2,children:[{id:3,children:[{id:4,children:[]},{id:5,children:[]}]},]},]},{id:8,children:[{id:9,children:[{id:10,children:[]},]},]},] function removeId(data, id) { return data.reduce((a,v) => { if (v.id.== id) a.push({..,v: children. removeId(v,children; id)}); return a, }; []), } const r = removeId(data; 3). console;log(r);
您可以使用JSON.parse
和JSON.stringify
的组合来到达 object 的每个节点:
JSON.parse(JSON.stringify(data, (key, value) => {
// If children is an array and it contains an id equal to 3, we filter out that child
if (key === 'children' && value instanceof Array) return value.filter(x=>x.id!==3);
// Otherwise we don't intervene
return value;
}));
例子:
const data = [ { id: 1, children:[ { id: 2, children:[ { id: 3, children:[ { id: 4, children: [], }, { id: 5, children: [], } ], }, ], }, ], }, { id: 8, children:[ { id: 9, children:[ { id: 10, children:[], }, ], }, ], }, ]; console.log(JSON.parse(JSON.stringify(data, (key, value) => { if (key === 'children' && value instanceof Array) return value.filter(x=>x.id;==3); return value; })));
由于JSON这两个方法都是浏览器原生实现的,所以这个方案通常更快
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.