一、树形数据转扁平化
<script>
let arr = [
{
id: "001",
name: 'zs',
children: [
{
id: '001-1',
name: 'zs-1',
children: [
{
id: '001-1-1',
name: 'zs-1-1',
children: [
{
id: '001-1-1-1',
name: 'zs-1-1-1'
},
{
id: '001-1-1-2',
name: 'zs-1-1-2'
}
]
},
{
id: '001-2-2',
name: 'zs-2-2',
children: [
{
id: '001-2-2-2',
name: 'zs-2-2-2'
},
{
id: '001-3-3-3',
name: 'zs-3-3-3'
}
]
}
]
},
{
id: '001-2',
name: 'zs-2',
children: [
{
id: '001-2-1',
name: 'zs-2-1',
children: [
{
id: '001-2-1-1',
name: 'zs-2-1-1'
},
{
id: '001-2-1-2',
name: 'zs-2-1-2'
}
]
},
{
id: '001-3-1',
name: 'zs-3-2',
children: [
{
id: '001-3-2-2',
name: 'zs-3-2-2'
},
{
id: '001-3-3-3',
name: 'zs-3-3-3'
}
]
}
]
},
]
},
{
id: "002",
name: 'ls',
children: [
{
id: '002-1',
name: 'ls-1',
children: [
{
id: '002-1-1',
name: 'ls-1-1'
}
]
},
{
id: '002-2',
name: 'ls-2',
children: [
{
id: '002-2-1',
name: 'ls-2-1'
}
]
}
]
},
]
//forEach方法
function treeToArr(data, parentId, res = []) {
data.forEach(v => {
res.push({
id: v.id,
parentId: parentId,
name: v.name
})
if (v.children && v.children.length) {
treeToArr(v.children, v.id, res)
}
})
return res
}
console.log(treeToArr(arr))
//reduce方法
function treeToArr(data, parentId) {
return data.reduce((res, { id, name, children }) => {
res.push({ id, parentId, name });
if (children && children.length) {
res = [...res, ...treeToArr(children, id)];
}
return res;
}, []);
}
</script>
二、树形数据转扁平化
<script>
const dataList = [
{
id:1,
name:'小王',
children:[
{
id:12,
name:'小黑',
children:[
{
id:121,
name:'小白'
},
{
id:122,
name:'小张'
}
]
}
]
},
{
id:2,
name:'小张',
children:[
{
id:22,
name:"小刘",
children:[
{
id:221,
name:'小明'
},
{
id:222,
name:'小孙'
}
]
}
]
}
]
const result = dataList.reduce(function (prev, cur) {
prev.push({
id: cur.id,
name: cur.name,
pid:cur.pid
})
cur.children && cur.children.forEach(v => {
v.pid = cur.id
arguments.callee(prev, v)
})
return prev
}, [])
console.log('result', result);
//或者
function flatten(data) {
return data.reduce((prev, cur) => {
prev.push({ id: cur.id, name: cur.name });
if (cur.children) {
prev.push(...flatten(cur.children));
}
return prev;
}, []);
}
const flatData = flatten(dataList);
console.log('flatData', flatData);
</script>
结果:
三、扁平数据转化树形数据
<scrpit>
const data = [
{ id: 1, name: '小王'},
{ id: 12, name: '小黑', parentId: 1 },
{ id: 121, name: '小白', parentId: 12 },
{ id: 122, name: '小张', parentId: 12 },
{ id: 2, name: '小张'},
{ id: 22, name: '小刘', parentId: 2 },
{ id: 221, name: '小明', parentId: 22 },
{ id: 222, name: '小孙', parentId: 22 },
]
const newData = data.reduce(function(pre,curr, i , arr) {
curr.children = arr.filter(v=> v.parentId === curr.id)
if(!curr.parentId) {
pre.push(curr)
}
return pre
},[])
console.log('newData',newData);
//封装
function buildTree(data) {
const map = {};
const roots = [];
for (const node of data) {
node.children = [];
map[node.id] = node;
if (!map[node.parentId]) {
roots.push(node);
} else {
map[node.parentId].children.push(node);
}
}
return roots;
}
console.log(buildTree(data));
</script>