封裝函數(shù)
// 傳入 id、樹形結(jié)構(gòu)數(shù)據(jù)
export function getParentTree(id, tree) {
let arr = [] //要返回的數(shù)組
for (let i = 0; i < tree.length; i++) {
let item = tree[i]
arr = []
arr.push(item) //保存當前節(jié)點id
if (id== item.id) {
//判斷當前id是否是默認id
return arr //是則退出循環(huán)、返回數(shù)據(jù)
} else {
//否則進入下面判斷,判斷當前節(jié)點是否有子節(jié)點數(shù)據(jù)
if (item.children && item.children.length > 0) {
//合并子節(jié)點返回的數(shù)據(jù)
arr = arr.concat(getParentTree(id, item.children ? item.children : []))
console.log(arr)
if (arr.map(item2 => (item2 ? item2.id : '')).includes(id)) {
//如果當前數(shù)據(jù)中已包含默認節(jié)點,則退出循環(huán)、返回數(shù)據(jù)
return arr
}
}
}
}
調(diào)用函數(shù)
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))
文章來源地址http://www.zghlxwxcb.cn/news/detail-438748.html
文章來源:http://www.zghlxwxcb.cn/news/detail-438748.html
到了這里,關(guān)于js 樹形結(jié)構(gòu)根據(jù)id獲取父級節(jié)點元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!