function getAncestors(result, id, arr) {
arr.some(item => {
if (item.id === id) {
result.unshift(item.parentId);
getAncestors(result, item.parentId, arr);
return true;
}
});
return result;
}
var ancestorList = [
{ id: 11, parentId: 1 },
{ id: 12, parentId: 1 },
{ id: 111, parentId: 11 },
{ id: 121, parentId: 12 },
{ id: 1211, parentId: 121 }
];
var ancestors = getAncestors([], 1211, ancestorList);
console.log(ancestors); //[1, 12, 121]
递归获取祖先id集合
最新推荐文章于 2023-03-23 16:53:36 发布