我有以下数据
const data = [
{ id: 56, parentId: 62, text: "56" },
{ id: 81, parentId: 80, text: "81" },
{ id: 74, parentId: null, text: "74" },
{ id: 76, parentId: 80, text: "76" },
{ id: 63, parentId: 62, text: "63" },
{ id: 80, parentId: 86, text: "80" },
{ id: 87, parentId: 86, text: "87" },
{ id: 62, parentId: 74, text: "62" },
{ id: 86, parentId: 74, text: "86" },
{ id: 1008, parentId: 81, text: "1008" },
{ id: 1009, parentId: 81, text: "1009" },
];
我的尝试:
我先假设找 "80"
let targetList = data.filter((item)=> item.text == "80");
let node1 = [];
for(let item of data){
if(item.parentId == targetList[0].id){
node1.push(item)
}
}
let node2 = data.filter((v) => {
return (
node1.filter((b) => {
return v.parentId == b.id;
}).length >= 1
);
});
let result = [...node1,...node2]
得到结果:
[
{ id: 80, parentId: 86, text: "80" },
{ id: 81, parentId: 80, text: "81" },
{ id: 76, parentId: 80, text: "76" },
{ id: 1008, parentId: 81, text: "1008" },
{ id: 1009, parentId: 81, text: "1009" },
]
没错实现了,但是层级更多的话,需要写的for更多。
我想到递归,但是 出口条件 想不通,一直死循环。
我想要的结果,就是 获取 目标项 还有 目标项各个子项
感谢您的帮助.
比较典型的
list
转tree
的简单应用:包含自己的查询: