展平带有嵌套子对象的对象数组

时间:2019-11-18 06:15:21

标签: javascript arrays

我一直在尝试创建一个通用函数,该函数可以展平一组对象,但是每一次都会失败。 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},
]

3 个答案:

答案 0 :(得分:0)

您可以尝试

    const ua: string = req.headers['user-agent']!

答案 1 :(得分:0)

所以有Array.prototype.flat,但这不涉及将一个键(应该知道,哪个键)扁平化的对象列表。

但是您总是可以借助Array.prototype.reduce实现自己的目标:

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

function myFlat(a, prefix = '') {  
  return a.reduce(function (flattened, {path, component, children}) {
    path = prefix + path;
    
    return flattened
      .concat([{path, component}])
      .concat(children ? myFlat(children, path) : []);
  }, []);
}

console.log(myFlat(arr));

答案 2 :(得分:0)

对于上面的示例,应该这样做。

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)