// 通过后端返回的最后一级id,找到前面几级的id
// 通过最后一级id逐层找到他对应的父级
// 通过这个方法可以得到一个数组,但是是反序的
findParentId(list, id, result = []) {
for (let item of list) {
console.log(`strart=========id是${id}数据是`,JSON.stringify(item))
if (item.value === id) {
result.push(id);
return result;
}
if (item.children && item.children.length) {
const temp = this.findParentId(item.children, id, result);
if (temp) {
result.push(item.value);
return result;
}
}
}
return null;
},
list: [
{
value: 1,
label: '1东南2',
children: [
{
value: 2,
label: '2上海',
children: [
{ value: 3, label: '3普陀' },
]
}
]
}
]
const res=this.findParentId(this.list,3)
console.log(res.reverse()) //[1,2,3]
正序的
list: [
{
value: 4,
label: '东南'
},
{
value: 1,
label: '东南',
children: [
{
value: 2,
label: '上海',
children: [
{ value: 3, label: '普陀' },
]
},
{
value: 7,
label: '江苏',
children: [
{ value: 8, label: '南京' },
{ value: 9, label: '苏州' },
]
}
]
}
]
getParentsById(list, id) {
for (let i in list) {
console.log(`strart=========id是${id}和list的${Number(i)+1}条数据,数据是`,JSON.stringify(list[i]))
if (list[i].value == id) {
return [list[i].value]
}
if (list[i].children) {
let node = this.getParentsById(list[i].children, id)
if (node !== undefined) {
// 追加父节点
node.unshift(list[i].value)
return node
}
}
}
},
const backRes=[4,3,9]
let newArr=[]
backRes.forEach(item=>{
let res= this.getParentsById(this.list,item)
newArr.push(res)
})
this.value=newArr
[[4],[1,2,3],[1,7,9]]