目錄
- 樹結(jié)構(gòu)-扁平化
{
text: '一級', // 要顯示的文本
value: 1, // 唯一值
checked: false, // 選中轉(zhuǎn)態(tài)
children: [{
text: '二級-1',
value: 11,
checked: false,
children: [{
text: '三級-1',
value: 111,
checked: false,
}]
}, {
text: '二級-2',
value: 12,
checked: false,
}]
}
需要轉(zhuǎn)化成以下格式
[ { text: '一級',
value: 1,
checked: false,
disabled: false,
showSign: true,
parent: null },
{ text: '二級-1',
value: 11,
checked: false,
disabled: false,
parent: 1 },
{ text: '三級-1',
value: 111,
checked: false,
disabled: false,
parent: 11 },
{ text: '二級-2',
value: 12,
checked: false,
disabled: false,
parent: 1 } ]
代碼實(shí)現(xiàn)
let tree = {
text: '一級', // 要顯示的文本
value: 1, // 唯一值
checked: false, // 選中轉(zhuǎn)態(tài)
children: [{
text: '二級-1',
value: 11,
checked: false,
children: [{
text: '三級-1',
value: 111,
checked: false,
}]
}, {
text: '二級-2',
value: 12,
checked: false,
}]
}
var result = []
function treeToLine(tree, treeKey, isRoot = true, root = null) {
if (!tree || !tree.children) return result
let obj = {}
for (let key in tree) {
if (tree.hasOwnProperty(key) && key !== 'children') {
obj[key] = tree[key]
}
}
obj.parent = isRoot ? null : root[treeKey]
result.push(obj)
for (let child of tree.children) {
if (child && child.children) {
treeToLine(child, treeKey, false, tree)
} else if (child && !child.children){ // 最后一層
child.parent = tree[treeKey]
result.push(child)
return result
}
}
}
console.log(treeToLine(tree, 'value'))
其中函數(shù)第二個參數(shù)為每層樹的唯一值乍恐,用于parent進(jìn)行標(biāo)識所屬的父節(jié)點(diǎn)辆琅。
- 扁平化-樹結(jié)構(gòu)
將上述扁平化數(shù)據(jù)格式化成樹狀數(shù)據(jù):
實(shí)現(xiàn)代碼:
function lineToTree(data, value = 'value', parentId = 'parent') {
let children = 'children'
let valueMap = [], tree = []
data.forEach(v => {
valueMap[v[value]] = v
})
data.forEach(v => {
let parent = valueMap[v[parentId]]
if(parent) {
!parent[children] && (parent[children] = [])
parent[children].push(v)
} else {
tree.push(v)
}
})
return tree
}
其中參數(shù)value是樹狀結(jié)構(gòu)的唯一標(biāo)識,parentId是父節(jié)點(diǎn)的鍵值苇羡。
1000個節(jié)點(diǎn)權(quán)限樹性能優(yōu)化
- 組裝后臺返回的數(shù)據(jù)結(jié)構(gòu)
-
通過關(guān)鍵字搜索時遍歷tree 對比節(jié)點(diǎn)下關(guān)鍵字是否存在