//传入参数:需要遍历的对象,需要匹配的id,获取所有的父级节点的Id
function findIdList(data2, id, children = 'children', level = 0) {
var arrRes = [];
let obj = {
id: 0,
[children]: data2
}
let rev = (data, id, level) => {
if (!data || !data[children] || !data[children].length) {
return;
}
for (var i = 0; i < data[children].length; i++) {
let item = data[children][i];
if (item.id == id) {
// 将匹配到的结果保存到数组
arrRes.unshift({ level, activeId: item.id });
// 递归它的父级
rev(obj, data.id, 0);
break;
} else if (item[children] && item[children].length > 0) {
//如果有子集,则把子集作为参数重新执行本方法
rev(item, id, level + 1);
}
}
};
rev(obj, id, level);
return arrRes;
}
let list = [
{id: 1, children: [
{id: 11, children: [{id: 12}]}
]},
{id: 2, children: [{id:21, children: [{id: 31}]}]}
]
let b = findIdList(list, 21)
console.log(b) // [ { level: 0, activeId: 2 }, { level: 1, activeId: 21 } ]