急求!!!!js 对树形结构数据根据某一属性进行过滤 获取新的树形结构感激不尽

需求如上现在有数据如下
data=[
{
id:0,
event:'事件1',
timeLine:50,
comment:'无',
age:13
},
{
id:1,
event:'事件1',
timeLine:100,
comment:'无',
age:13
children:[
{
id:2,
event:'事件2',
timeLine:10,
comment:'无',
age:11
},
{
id:3,
event:'事件3',
timeLine:90,
comment:'无',
age:13
children:[
{
id:4,
event:'事件4',
timeLine:5,
comment:'无',
age:17
},
{
id:5,
event:'事件5',
timeLine:10,
comment:'无',
age:13
},
{
id:6,
event:'事件6',
timeLine:75,
comment:'无',
age:13
children:[
{
id:7,
event:'事件7',
timeLine:50,
comment:'无',
age:13
children:[
{
id:71,
event:'事件71',
timeLine:25,
comment:'xx',
age:18
},
{
id:72,
event:'事件72',
timeLine:5,
comment:'xx',
age:13
},
{
id:73,
event:'事件73',
timeLine:20,
comment:'xx',
age:15
}
]
},
{
id:8,
event:'事件8',
timeLine:25,
comment:'无',
age:19
}
]
}
]
}
]
}
]
现在希望根据age是13的属性对data进行过滤,取得新的树形结构,求一个递归方法
智慧大石
浏览 1844回答 2
2回答

婷婷同学_

用递归写了个,人工核对了一下输出似乎没有问题。不排除在使用其他数据的时候会发生错误。反正思路在,如果有错改改应该不困难。/***递归过滤节点,生成新的树结构*@param{Node[]}nodes要过滤的节点*@param{node=>boolean}predicate过滤条件,符合条件的节点保留*@return过滤后的节点*/functiondeal(nodes,predicate){//如果已经没有节点了,结束递归if(!(nodes&&nodes.length)){return[];}constnewChildren=[];for(constnodeofnodes){if(predicate(node)){//如果节点符合条件,直接加入新的节点集newChildren.push(node);node.children=deal(node.children,predicate);}else{//如果当前节点不符合条件,递归过滤子节点,//把符合条件的子节点提升上来,并入新节点集newChildren.push(...deal(node.children,predicate));}}returnnewChildren;}constresult=deal(data,node=>node.age===13);console.log(JSON.stringify(result,null,4));输出结果太长,用一个示意的树来表示:/|--0`--1`--3|--5`--6`--7`--72
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript