原始数据
节点的id 和可以确定父子关系的 parentId
const treeData = [
{
id: '1',
parentId: '',
name: '红——水果',
identity: '红方'
},
{
id: '1-1',
name: '红-水果-红色的',
identity: '红方',
parentId: '1'
},
{
id: '1-1-1',
name: '红-水果-红色的-苹果',
identity: '红方',
parentId: '1-1'
},
{
id: '1-2',
name: '红-水果-绿色的',
identity: '红方',
parentId: '1'
},
{
id: '1-2-1',
name: '红-水果-绿色的-西瓜',
identity: '红方',
parentId: '1-2'
}
]
listTotree
function buildTree(data, parentId = '') {
const tree = []
for (const item of data) {
if (item.parentId === parentId) {
const children = buildTree(data, item.id)
if (children.length) {
item.children = children
}
tree.push(item)
}
}
return tree
}
treeToList
function flattenTree(tree, result = []) {
for (const node of tree) {
const { id, parentId, children, ...rest } = node
result.push({ id, parentId, ...rest })
if (children) {
flattenTree(children, result)
}
}
return result
}
const flatData = flattenTree(treeData)
console.log(flatData)
tree结构数据 过滤
过滤条件:node节点中 type!==100|| xslx===2
const formatTree=(data) => {
return data.filter(item => {return item.Type!=='100'||item.xslx==='2'}).map(item => {
item=Object.assign({},{...item})
if(item.children) item.children=formatTree(item.children)
})
}
tree节点 过滤成扁平数组
过滤叶子节点
function findLeafNodes(nodes: ChatTreeOption[], result: ChatTreeOption[]) {
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
if (node.isLeaf) {
result.push(node); // 如果当前节点是叶子节点,则把当前节点的信息存入result列表
}
else {
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
findLeafNodes(node.children, result); // 递归调用子节点,查找所有叶子节点
}
}
}
}
}