根据已有子级key,找到它的所有对应的父级们的集合。
-
比如我们现在有 let keys = [‘group300’,‘group301’,‘group302’],我们要找到它们的父级,然后再找爷级,以此类推。this.parentsKeyList:[]存储它们。
-
我们先看下初始数据data树的结构:
const data = {
"key": "root",
"type": "root",
"name": "root",
"child": [
{
"key": "competition01",
"type": "competition",
"name": "菜菜大赛",
"child": [
{
"key": "area100",
"type": "area",
"name": "华南赛区",
"child": [
{
"key": "contest200",
"type": "contest",
"name": "挑战赛",
"child": [
{
"key": "group300",
"type": "group",
"name": "少儿组",
"child": []
},
{
"key": "group301",
"type": "group",
"name": "小学组",
"child": []
},
]
},
]
},
]
},
{
"key": "competition02",
"type": "competition",
"name": "花花大赛",
"child": [
{
"key": "area101",
"type": "area",
"name": "东北赛区",
"child": [
{
"key": "contest201",
"type": "contest",
"name": "创意赛",
"child": [
{
"key": "group302",
"type": "group",
"name": "初中组",
"child": []
},
]
},
]
},
]
},
{
"key": "competition03",
"type": "competition",
"name": "坤坤大赛",
"child": [
{
"key": "area103",
"type": "area",
"name": "海外赛区",
"child": [
{
"key": "contest202",
"type": "contest",
"name": "科技赛",
"child": [
{
"key": "group304",
"type": "group",
"name": "高中组",
"child": []
},
]
},
]
},
]
},
]
}
//查找父级kye集合
bindFindKeys(data, val) {
let [arr,newArr] = [[],[]];
let list = data.child;
if (!list || !val) {
return ''
}
let findParent = (item, nodeKey, parentVal) => {
// console.log(item, nodeKey, parentVal)
for (let i = 0; i < item.length; i++) {
let node = item[i];
if (node.key === nodeKey) {
arr.unshift(nodeKey);
if (nodeKey === list[0].key) {
break
}
findParent(list, parentVal);
break
} else {
if (node.child) {
findParent(node.child, nodeKey, node.key);
}
continue
}
}
return arr;
}
newArr = findParent(list, val);
this.parentsKeyList = Array.from(new Set([...this.parentsKeyList,...newArr]));
return this.parentsKeyList; //存储去重一下
},
使用:
//假如我们要找keys里面的父级key们
let keys = ['group300','group301','group302'];
for(let v of keys){
this.bindFindKeys(data,v);
}
打印一下: