/ 定义处理函数
function processArray(arr) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i].children)) {
if (arr[i].children.length > 4) {
let newItem = arr[i].children[4];
newItem.name="展示更多"
arr[i].children = arr[i].children.slice(0, 4);
arr[i].children.push(newItem)
}
processArray(arr[i].children);
}
}
}
// 原始四维数组
const originalArray = [
{
name: "A",
children: [
{
name: "B",
children: [
{ name: "C1" },
{ name: "C2" },
{ name: "C3" },
{ name: "C4" },
{ name: "C5" }
]
},
{ name: "B2" },
{ name: "B3" },
{ name: "B4" },
{ name: "B5" },
]
},
{
name: "D",
children: [
{ name: "E" },
{ name: "F" }
]
}
];
console.log(JSON.parse(JSON.stringify(originalArray)));
// 处理数组
processArray(originalArray);
// 输出处理后的数组
console.log(originalArray);
关于递归---小栗子
最新推荐文章于 2024-08-19 15:26:06 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)