<script>
var arr = [{
id: 1,
children: [{
id: 11,
children: [{
id: 111
}]
}, {
id: 12,
children: [{
id: 121
}]
}, {
id: 13,
children: [{
id: 131
}]
}]
}]
function getLine(list, id) {
var map = new Map();
var tree = function(list, id, parentId) {
if(!list || !list.length) {
return null;
}
for(let item of list) {
map.set(item.id, parentId);
if(item.id === id) {
return id;
}
const _ID = tree(item.children, id, item.id);
if(_ID || _ID === 0) {
return _ID;
}
}
return null;
}
let o = tree(list, id, null);
var arr = [o];
while(map.get(o)) {
arr.push(map.get(o));
o = map.get(o);
}
return arr;
}
const arr2 = getLine(arr,131);
console.log(arr2);
</script>
网友评论