封裝函數 // 傳入 id、樹形結構數據 export function getParentTree(id, tree) { let arr = [] //要返回的數組 for (let i = 0; i < tree.length; i++) { let item = tree[i] arr = ...
封裝函數
// 傳入 id、樹形結構數據
export function getParentTree(id, tree) {
let arr = [] //要返回的數組
for (let i = 0; i < tree.length; i++) {
let item = tree[i]
arr = []
arr.push(item) //保存當前節點id
if (id== item.id) {
//判斷當前id是否是預設id
return arr //是則退出迴圈、返回數據
} else {
//否則進入下麵判斷,判斷當前節點是否有子節點數據
if (item.children && item.children.length > 0) {
//合併子節點返回的數據
arr = arr.concat(getParentTree(id, item.children ? item.children : []))
console.log(arr)
if (arr.map(item2 => (item2 ? item2.id : '')).includes(id)) {
//如果當前數據中已包含預設節點,則退出迴圈、返回數據
return arr
}
}
}
}
調用函數
const treeData = [{
name: '1',
id: 1,
children: [{
name: '1-1',
id: 2,
children: [{
name: '1-1-1',
id: 4,
}],
name: '1-2',
id: 3,
children: [{
name: '1-2-1',
id: 5,
}],
}]
},{
name: '2',
id: 6,
children: [{
name: '2-1',
id: 7,
children: [{
name: '2-1-1',
id: 9,
}],
name: '2-2',
id: 8,
children: [{
name: '2-2-1',
id: 10,
}],
}]
}]
console.log(getParentTree(5, treeData))
本文來自博客園,作者:戰立標,轉載請註明原文鏈接:https://www.cnblogs.com/zhanlibiao/p/17388752.html