前言
学习一下相关知识
- 递归:一种算法,可查询相关材料。
- 拓展运算符: es6相关方法,可将数组展开
console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
- concat: 数组的连接方法。
[1,2,3].concat(4,5)
// [1, 2, 3, 4, 5]
[1,2,3].concat([4],[5])
// [1, 2, 3, 4, 5]
先上代码
const arr = [
{
id: 1,
children: [
{
id: 2,
children: [
{
id: 3,
children: []
}
]
},
{
id: 6,
children: []
}
]
},
{
id: 4,
children: [
{
id: 5,
children: []
}
]
}
];
// 递归方法
const flatJson = (arr, pId = 0) => {
return [].concat(...arr.map(item => {
const temp = JSON.parse(JSON.stringify(item.children))
delete item.children
return [].concat({ ...item, pId }, ...flatJson(temp, item.id))
}))
}
console.log(flatJson(arr));
//
[ { "id": 1, "pId": 0 }, { "id": 2, "pId": 1 }, { "id": 3, "pId": 2 }, { "id": 6, "pId": 1 }, { "id": 4, "pId": 0 }, { "id": 5, "pId": 4 }]
简单讲解一下过程
flatJson方法接收两个参数,arr:需要处理的数组,pId: 父级ID,没有父级默认为0
arr数组进行map遍历,然后拿到子级的对象,深拷贝一下children(因为要delete,浅拷贝无法保存)
然后用concat连接之后,就变成了 [{ ...item, pId }, ...flatJson(temp, item.id)]
进行flatJson进行递归处理子级,重复上诉操作返回 [{ ...item, pId }, { ...item, pId } ...flatJson(temp, item.id)]
一直进行递归处理,然后结果就是[{ ...item, pId }, { ...item, pId } , { ...item, pId },...] 此时可能会有疑问,arr.map前边的作用是什么?
map方法最终的结果是一个数组,但是现在map方法return 出去的就是一个数组,所以当前map方法得到的是一个二维数组,[ [{}] , [{}], [{}], ...[{}] ], 所以用拓展运算符展开之后就成了[{}],[{}],[{}],[{}]...,然后进行concat连接之后,就变成了[{},{},{}...]
版权声明:本文为CSDN博主「凯宾」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/weixin_4159…
本文参照CSDN博主「凯宾」的原创文章进行编写