数组对象扁平化
2021-03-24 本文已影响0人
北上广_d8bd
const arr = [
{
id: 1,
title: "课程 1",
children: [
{ id: 4, title: "课程 1-1" },
{
id: 5,
title: "课程 1-2",
children: [
{ id: 6, title: "课程 1-2-1" },
{ id: 7, title: "课程 1-2-2" },
],
},
],
},
{ id: 2, title: "课程 2" },
{ id: 3, title: "课程 3" },
];
function flaten(arr) {
return arr.reduce((p, v, i) => {
for (let i = 0; i < p.length; i++) {
if (p[i].children) {
delete p[i].children
}
}
return p.concat(v.children ? flaten(v.children).concat(v) : v);
}, [])
}
console.log(flaten(arr))
// reduce 功能很强大呦;