根据某字段和值递归查找所有父级
//name——某字段,value——值
function getParentId(list, name, value) {
for (let i in list) {
if(list[i][name] == value){
return [list[i]]
}
if(list[i].children){
let node = getParentId(list[i].children, name, value);
if(node!== undefined){
return node.concat(list[i])
}
}
}
}
树的结构:
let tree = [
{
id: '1',
name: '北京市',
children: [{
id: '1.1',
name: '朝阳区',
}]
},
{
id: '2',
name: '上海市',
children: [{
id: '2.1',
name: '黄浦区',
children: [{
id: '2.1.1',
name: '东区街道',
},{
id: '2.1.2',
name: '永和街道',
}]
}]
},
{
id: '3',
name: '天津市',
children: [{
id: '3.1',
name: '南开区',
}]
},
]
调用方法:
let arr = getParentId(tree, 'id', '2.1.2');
let arr1 = getParentId(tree, 'name', '黄浦区');