js 实现一个方法,参数传入一个深度嵌套的数组对象,传入的对象例如[ { name: '321', age: '21', children: [] }, { name: '321', age: '21', children: [ { name: '321', age: '21', children: [ { name: '321', age: '21', } ] } ] }, { name: '321', age: '21', children: [ { name: '321', age: '21', children: [] }, ] }, ],对象中有children属性,当children这个属性的数组为空时,返回的新数组对象中就不存在children属性
时间: 2023-05-25 11:05:01 浏览: 72
function flatten(arr) {
return arr.reduce((prev, curr) => {
if (curr.children && curr.children.length > 0) {
prev.push({
name: curr.name,
age: curr.age,
children: flatten(curr.children)
});
} else {
prev.push({
name: curr.name,
age: curr.age
});
}
return prev;
}, []);
}
const originalArray = [
{
name: '321',
age: '21',
children: []
},
{
name: '321',
age: '21',
children: [
{
name: '321',
age: '21',
children: [
{
name: '321',
age: '21'
}
]
}
]
},
{
name: '321',
age: '21',
children: [
{
name: '321',
age: '21',
children: []
},
]
},
];
const flattenedArray = flatten(originalArray);
console.log(flattenedArray); // Output: [{"name":"321","age":"21"}, {"name":"321","age":"21","children":[{"name":"321","age":"21","children":[{"name":"321","age":"21"}]}]}, {"name":"321","age":"21","children":[{"name":"321","age":"21"}]}]
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)