const data = [
{ id:1, pid:0, text:1, children:[{ id:2, pid:1, text:2, children:[{ id:3, pid:2, text:3, children:[]
}]
}]
}
]//怎么查找id的父级的index索引id=3父级2 所在数组index为0,在上父级的id1,所在数组的index 0,直到最顶一层//输入id 3//返回 [0,0,0] 索引的数组
1 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
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; i++) {
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]添加回答
举报
0/150
提交
取消
