const data = [
{
id:1,
pid:0,
text:1,
children:[{
id:2,
pid:1,
text:2,
children:[{
id:3,
pid:2,
text:3,
children:[]
}]
}]
},
{
id: 4,
pid: 0,
text: 4,
children: [{
id: 5,
pid: 4,
text: 5,
children: [{
id: 6,
pid: 5,
text: 6
}]
}, {
id: 7,
pid: 4,
text: 7,
children: [{
id: 8,
pid: 7,
text: 8
}]
}]
}
]
function findIndexArray (data, id, indexArray) {
let arr = Array.from(indexArray)
for (let i = 0, len = data.length; i < len; iPP) {
arr.push(i)
if (data[i].id === id) {
return arr
}
let children = data[i].children
if (children && children.length) {
let result = findIndexArray(children, id, arr)
if (result) return result
}
arr.pop()
}
return false
}
findIndexArray(data, 3, []) // [0, 0, 0]
findIndexArray(data, 8, []) // [1, 1, 0]
findIndexArray(data, 7, []) // [1, 1]
const data = [
{
id:1,
pid:0,
text:1,
children:[{
id:2,
pid:1,
text:2,
children:[{
id:3,
pid:2,
text:3,
children:[]
}]
}]
}
]
let parentList = [];
function getNode(list, nodeId) {
for (var i = 0; i < list.length; iPP) {
let obj = list[i];
if(obj.id == nodeId){
parentList.unshift(i); //pid=0,pid=1,pid=2parentList.push(i)
getNode(data, obj.pid);
break;
}
if(obj && obj.children){
getNode(obj.children, nodeId);
}
}
}
getNode(data, 3);
console.log("", parentList); //[0,0,0]