Skip to main content

扁平数据结构转 Tree

打平的数据:

let arr = [
{id: 1, name: '部门1', pid: 0},
{id: 2, name: '部门2', pid: 1},
{id: 3, name: '部门3', pid: 1},
{id: 4, name: '部门4', pid: 3},
{id: 5, name: '部门5', pid: 4},
]

输出结果:

[
{
"id": 1,
"name": "部门1",
"pid": 0,
"children": [
{
"id": 2,
"name": "部门2",
"pid": 1,
"children": []
},
{
"id": 3,
"name": "部门3",
"pid": 1,
"children": [
// 结果 ,,,
]
}
]
}
]

递归

/**
* 递归查找,获取children
*/
const getChildren = (data, result, pid) => {
for (const item of data) {
if (item.pid === pid) {
const newItem = {...item, children: []};
result.push(newItem);
getChildren(data, newItem.children, item.id);
}
}
}

/**
* 转换方法
*/
const arrayToTree = (data, pid) => {
const result = [];
getChildren(data, result, pid)
return result;
}

使用方法:

console.log(arrayToTree(arr,0));

参考

扁平数据结构转 Tree

打平的数据:

const data = [
{ id: 1, pid: 0 },
{ id: 2, pid: 1 },
{ id: 3, pid: 1 },
{ id: 4, pid: 3 },
{ id: 5, pid: 4 },
]

输出结果:

{
id: 1,
pid: 0,
children:[
{
id: 2,
pid: 1,
children:[]
},
{
id: 3,
pid: 1,
children:[
{
id: 4,
pid: 3,
children:[
{
id: 5,
pid: 4,
children:[]
}
]
}
]
}
]
}

递归

// 不改变原数据data,需要提前进行深拷贝

// 1.先遍历获取最外层的父元素
const parentArr = data.filter(item => !item.pid);

// 2.递归生成树结构
const toTree = (parent, data) => {

// 3.递归生成子元素
// 直接改变原数据
parent.forEach(item => {
// 添加children属性
item.children = [];
let list = [];
// 4. 把pid拷贝到对应id中children中
data.forEach(i => {
if(i.pid && i.pid === item.id){
item.children.push(i);
list.push(i)
}

})
// 4.子元素/处理后data传入递归
toTree(list, data);
})
return parent
}

使用方法:

console.log(toTree(parentArr, data))

参考

扁平数据结构转 Tree

打平的数据:

var data = [{
id: 1,
parent_id: null
}, {
id: 2,
parent_id: 1
}, {
id: 3,
parent_id: 1
}, {
id: 4,
parent_id: 2
}, {
id: 5,
parent_id: 4
}];

输出结果:

{
id: 1,
parent_id: null,
children:[
{
id: 2,
parent_id: 1,
children: [
{
id: 4,
parent_id: 2,
children: [
{
id: 5,
parent_id: 4,
children: []
}
]
}
]
},
{
id: 3,
parent_id: 1,
children: []
}
]
}

递归

const nest = (items, id = null, link = 'parent_id') =>{
const list = items.filter(item => item[link] === id)
return list.map(item => ({ ...item,children:nest(items,item.id) }))
}

使用方法:

console.log(nest(data))

参考