const arr1 = [
{
id: 1,
name: '2',
children: [
{
id: 1,
name: '2',
children: []
},
{
id: 2,
name:'2'
}
]
},
{
id: 2,
name:'2'
}
];
// 定义一个递归函数来展平嵌套数组
function flatMapRecursive(array) {
return array.flatMap(item => {
// 提取当前项,不包含 children 属性
const { children, ...currentItem } = item;
// 展平当前项和它的 children
return children ? [currentItem, ...flatMapRecursive(children)] : [currentItem];
});
}
// 使用递归的 flatMap 函数展平嵌套数组 const flattenedArray = flatMapRecursive(arr1);
console.log(flattenedArray);