<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
const json = [
{
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" },
];
let arr = [];
function fn(j) {
j.forEach(item => {
arr.push(item)
//循环判断是否有children
if (item.children) {
//如果有 递归去除
fn(item.children)
}
})
arr.forEach(item => {
// 删除children
delete item.children
})
console.log(arr)
}
fn(json)
</script>
js数组平铺到对象中
最新推荐文章于 2024-04-08 10:18:23 发布