如何解决从子节点id中的子节点中查找父节点?
我有一个对象数组,其中有多个子节点,如何从子对象 id 中找到父对象。
[
{
id: "a1",name: "apple",subGroups: [
{
id: "a2",name: "apple-a",subGroups: [
{
id: "a3",name: "apple-b",subGroups: [
{
id: "a4",name: "apple-c",subGroups: [
{
id: "a5",name: "apple-d",subGroups: [
]
}
]
}
]
}
]
}
]
},{
id: "b2",name: "orange",subGroups: [
{
id: "b2",name: "orange-a",subGroups: [
{
id: "b3",name: "orange-b",subGroups: [
{
id: "b4",name: "orange-c",subGroups: [
{
id: "b5",name: "orange-d",subGroups: [
]
}
]
}
]
}
]
}
]
}
];
如果id = a4
,输出应该是:
[
{
id: "a1",subGroups: [
]
}
]
}
]
}
]
}
]
}
]
如果id = b3
,输出应该是:
[
{
id: "b2",subGroups: [
]
}
]
}
]
}
]
}
]
}
]
我试过了:
const find = (array,id) => (Array.isArray(array) ?
array : [array]).flatMap(o => o.id=== id? o : find(o.subGroups,id)),data = group,result = find(data,event.id);
解决方法
您可以分 3 个步骤完成:
- 使用递归技术来确定每个孩子的
parentID
像这样。
[
{"id": "a1","parentId": "a1"},{"id": "a2",...
{"id": "b2","parentId": "b2"},{"id": "b3","parentId": "b2"}
...
]
- 像这样通过
parentId
准确获取childID
const parentId = child_parent_Mapping.find(r => r.id === childID)?.parentId;
- 按
arr
过滤parentId
的结果。
let arr = [{ id: "a1",name: "apple",subGroups: [{id: "a2",name: "apple-a",subGroups: [{id: "a3",name: "apple-b",subGroups: [{id: "a4",name: "apple-c",subGroups: [{id: "a5",name: "apple-d",subGroups:[]}]}]}]}]},{ id: "b2",name: "orange",subGroups: [{id: "b2",name: "orange-a",subGroups: [{id: "b3",name: "orange-b",subGroups: [{id: "b4",name: "orange-c",subGroups: [{id: "b5",name: "orange-d",subGroups:[]}]}]}]}]}];
// Step 1
const flatItems = (arr,parentId = "") => {
return arr.flatMap(({id,subGroups}) => {
const childrens = flatItems(subGroups,parentId || id);
return [{id,parentId: parentId || id},...childrens];
});
};
const child_parent_Mapping = flatItems(arr);
const filter_arr = (childID) => {
// Step 2
const parentId = child_parent_Mapping.find(r => r.id === childID)?.parentId;
// Step 3
return arr.filter(r => r.id === parentId);
}
console.log({Child: "a1",output: filter_arr('a1')});
console.log({Child: "a4",output: filter_arr('a4')});
console.log({Child: "b3",output: filter_arr('b3')});
.as-console-wrapper { max-height: 100% !important; top: 0; }
我不知道这到底是不是想要的,但是从下面的代码中您可以找到ultimate 表示每个 child id
的最后一个父级:
const arr = [{ id: "a1",subGroups:[]}]}]}]}]}];
const res = [];
const id = "a4";
arr.map(obj=>{
const str = JSON.stringify(obj);
if(str.search(id)>-1){
res.push(obj);
}
})
console.log(res); //result array
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。