以下结构,通过41查找,拼接成11-21-31-41
const data = [{
id: 11,
pid: 'a1',
text: 11,
children: [{
id: 21,
pid: 'b1',
text: 21,
children: [{
id: 31,
pid: 'c1',
text: 31,
children: [{
id: 41,
pid: 'd1',
text: 41,
children: []
},
{
id: 42,
pid: 'd2',
text: 42,
children: []
}
]
},
{
id: 32,
pid: 'c2',
text: 32,
children: []
}
]
},
{
id: 22,
pid: 'b2',
text: 22,
children: []
}
]
},
{
id: 12,
pid: 'a2',
text: 12,
children: []
}
]
findIndexArray(data, id, indexArray) {
// 根据自身节点寻找父级
let arr = Array.from(indexArray);
for (let i = 0, len = data.length; i < len; i++) {
arr.push(data[i].name);
if (data[i].id === id) {
return arr;
}
let children = data[i].children;
if (children && children.length) {
let result = this.findIndexArray(children, id, arr);
if (result) return result;
}
arr.pop();
}
return false;
},
调用:
let name = this.findIndexArray(
this.data,
Number(this.form.department_id),
[]
).join("-");
不私藏,献上宝典:http://raboninco.com/1MsLW