const data = [
{
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 flatten(arr) {
let result = []
if (Array.isArray(arr)) {
for (let item of arr) {
if (item.children?.length) {
const item2 = JSON.parse(JSON.stringify(item))
delete item2.children
result.push(item2)
result = result.concat(flatten(item.children))
} else {
result.push(item)
}
}
}
return result
}
console.log(flatten(data))
js 数组扁平化
最新推荐文章于 2023-08-10 10:14:23 发布