Skip to main content

递归查找——通过某个属性从树结构中获取对象

const personArr = [
{
id: '001',
name: 'maimang',
children: [
{
id: '002',
name: 'Tom',
headImg: 'https://avatars1.githubusercontent.com/u/24405319?s=460&v=4',
},
{
id: '003',
name: 'Jerry',
headImg: 'https://avatars1.githubusercontent.com/u/24405319?s=460&v=4',
},
{
id: '006',
name: '业务部',
children: [
{
id: '007',
name: '小明',
headImg:
'https://avatars1.githubusercontent.com/u/24405319?s=460&v=4',
},
{
id: '008',
name: '小话',
headImg:
'https://avatars1.githubusercontent.com/u/24405319?s=460&v=4',
},
{
id: '009',
name: '小王',
headImg:
'https://avatars1.githubusercontent.com/u/24405319?s=460&v=4',
},
],
},
{
id: '010',
name: 'test',
headImg: 'https://avatars1.githubusercontent.com/u/24405319?s=460&v=4',
},
],
},
];
function getCurrentPart(id, items) {
let result;
for (var i in items) {
let item = items[i];
if (item.id == id) {
result = item.children;
break;
} else if (item.children) {
result = getCurrentPart(id, item.children);
}
}
return result;
}