寫在前面的話
昨兒忘拿電腦回家了,早晨來補~
(一)題目
将下面的數組鋪平
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)
}
}
浏覽器中列印如下
以上