Day46/100 (前端面试)如何将数组铺平?
写在前面的话
昨儿忘拿电脑回家了,早晨来补~
(一)题目
将下面的数组铺平
const data=[
{
id:1,
title:"课程1",
children:[
{id:4,title:"课程1-1"},
{
id:5,
title:"课程1-1",
children:[
{id:6,title:"课程1-2-1"},
{id:7,title:"课程1-2-2"},
]
},
]
},
{id:2,title:"课程2"},
{id:3,title:"课程3"}
]
期待的结果类似是
const formatData = [
{ id: 1, title: "课程1" },
{ id: 4, title: "课程1-1" },
{ id: 5, title: "课程1-2" },
{ id: 6, title: "课程1-2-1" },
{ id: 7, title: "课程1-2-2" },
{ id: 2, title: "课程2" },
{ id: 3, title: "课程3" },
];
(二)思路
1、遍历数组,找到有children节点的对象
将节点push到数组中;
2、删掉原数组中的children节点
3、递归
代码如下
for(let item of rs){
if(item.children){
for(let i of item.children){
rs.push(i)
}
delete item['children']
handle(rs)
}
}
浏览器中打印如下
![](https://img.haomeiwen.com/i19050589/cb20aa18c00c82cf.png)
以上