前言
记录一下用过的方法~ 对象数组扁平化,有别的方法可以评论区交流一下
代码如下:
const array = [{
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 steamroller(arr) {
var newArr = [];
arr.forEach(element => {
newArr.push(element)
if (element.children) {
newArr.push.apply(newArr, steamroller(element.children))
delete element.children
} else {
}
});
return newArr
}
console.log(steamroller(array))