Javascript 展平具有嵌套子对象的对象数组

Javascript 展平具有嵌套子对象的对象数组,javascript,arrays,Javascript,Arrays,我一直在尝试创建一个通用函数,它可以展平一组对象,但每次都失败了。JS不是我的母语。是否有人知道任何现有函数可以接受嵌套对象数组并输出扁平对象 输入: const arr = [ {path:'/foo', component: SomeComponent, children: [ {path:'/one', component: SomeComponent}, {path:'/two', component: SomeComponent}

我一直在尝试创建一个通用函数,它可以展平一组对象,但每次都失败了。JS不是我的母语。是否有人知道任何现有函数可以接受嵌套对象数组并输出扁平对象

输入:

const arr = [
    {path:'/foo', component: SomeComponent, children: [
            {path:'/one', component: SomeComponent},
            {path:'/two', component: SomeComponent},
            {path:'/three', component: SomeComponent},
    ]},
    {path: '/bar', component: SomeComponent}
]
预期产出:

const flattened_arr = [
    {path:'/foo', component: SomeComponent},
    {path:'/foo/one', component: SomeComponent},
    {path:'/foo/two', component: SomeComponent},
    {path:'/foo/three', component: SomeComponent},
    {path:'/bar', component: SomeComponent},
]
你可以试试这个

flattarr=arr=>{
常量结果=[];
arr.forEach(项目=>{
常量{path,component,children}=item;
push({path,component});
if(儿童)
结果:推挤(…压扁ARR(儿童));
});
返回结果;
}
所以有,但这不涉及对象列表,其中一个键(它如何知道,哪个键)应该展平

但你可以通过以下方式实现这一目标:

const SomeComponent='SomeComponent';
常数arr=[
{路径:'/foo',组件:SomeComponent,子级:[
{path:'/one',component:SomeComponent},
{path:'/two',component:SomeComponent},
{路径:'/three',组件:SomeComponent}
]},
{path:'/bar',component:SomeComponent}
];
函数myFlat(a,前缀=“”){
返回a.reduce(函数(展平,{path,component,children}){
路径=前缀+路径;
回程变平
.concat([{path,component}])
.concat(children?myFlat(children,path):[]);
}, []);
}

控制台日志(myFlat(arr))对于上面的示例,应该这样做

const result = []
arr.map((obj) => {
  if (obj.children) {
    const el = {...obj, ...{}}
    delete el.children
    result.push(el) 
    Object.values(obj.children).map((v, i) => {
      result.push(v)
    })
  } else {
    result.push(obj)
  }
})

console.log(result)
看看这个: