话不多说,直接上代码:
var list = [ {id:1,pid:0,name:'中国'}, {id:2,pid:0,name:'美国'}, {id:3,pid:1,name:'云南'}, {id:4,pid:3,name:'昆明'}, {id:5,pid:4,name:'盘龙区'}, {id:6,pid:5,name:'北辰小区'}, ]; function findAncestry (arr, id) { var temp = [] var forFn = function (list, id) { for (var i = 0; i < list.length; i++) { var item = list[i] if (item.id === id) { temp.push(item) forFn(list, item.pid) break } else { if (item.children) { forFn(item.children, id) } } } } forFn(arr, id) return temp } var allParent = findAncestry(list,6); console.log(allParent);
打完收工。