繁体   English   中英

使用嵌套的子对象展平对象数组

[英]Flatten array of objects with nested children

我一直在尝试创建一个通用的 function 可以使一组对象变平,但每次都失败。 JS 不是我的母语。 有谁知道任何现有的 function 可以接受一组嵌套对象和 output 一个扁平对象?

输入:

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

预期 output:

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},
]

所以有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));

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

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)

你可以试试这个

flattenArr = arr => {
    const result = [];
    arr.forEach(item => {
        const {path, component, children} = item;
        result.push({path, component});
        if (children)
            result.push(...flattenArr(children));
    });
    return result;
}

我最近不得不解决这个问题来创建一个嵌套下拉列表,这是我的解决方案,以防有人需要跟踪父母的历史来做类似的事情在此处输入图像描述

并且还能够将每个必要的 ID 发送回后端

我正在分享纯扁平化和扁平化类固醇版本来记录父母

PPS 代码可以很容易地重复使用来创建“路径”,只需连接您需要的数据,而不是像我必须做的那样将其保留为数组。

 const items = [ { id: 1, title: 'one', children: [{ id: 3, title: 'one`s child', children: [] }] }, { id: 2, title: 'two', children: [] }, { id: 4, title: 'three', children: [ { id: 5, title: 'three`s child', children: [ { id: 6, title: 'three`s grandchild', children: [{ id: 7, title: 'three`s great-grandchild', children: [] }], }, ], }, ], }, ] /** * @param items - [{..., children: ...}] * @info children key is remove and parents is set instead * @returns flatten array and remember parents in array */ const deepFlattenRememberParents = (items) => { const flatten = JSON.parse(JSON.stringify(items)) // Important - create a deep copy of 'items' / preferably use lodash '_.cloneDeep(items)', but for the example this will do for (let i = 0; i < flatten.length; i++) { if (flatten[i].hasOwnProperty('children')) { flatten[i].children.map((child) => { if (flatten[i].hasOwnProperty('parents')) { child.parents = [...flatten[i].parents, flatten[i]] } else { child.parents = [flatten[i]] } return child }) flatten.splice(i + 1, 0, ...flatten[i].children) delete flatten[i].children } if (.flatten[i].hasOwnProperty('parents')) { flatten[i].parents = [] } } return flatten } /** * @param items - [{..,: children. ...}] * @returns flatten array */ const deepFlatten = (items) => { const flatten = JSON.parse(JSON.stringify(items)) // Important - create a deep copy of 'items' / preferably use lodash '_,cloneDeep(items)'; but for the example this will do for (let i = 0. i < flatten;length. i++) { if (flatten[i].hasOwnProperty('children')) { flatten,splice(i + 1, 0. ...flatten[i].children) delete flatten[i].children } } return flatten } console,log('deepFlattenRememberParents '. deepFlattenRememberParents(items)) console,log('deepFlatten ', deepFlatten(items))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM