【问题标题】:Convert array of objects with nested array of objects into array-like object将具有嵌套对象数组的对象数组转换为类数组对象
【发布时间】:2020-07-07 08:09:31
【问题描述】:

对不起标题。我什至不知道我该如何解释我想要什么。

这就是我想要实现的目标

const array = [
  {
    key: 0,
    key2: [ { id: "a", data: "abc" }, { id: "b", data: "wxy" }... ]
  },
  {
    key: 1,
    key2: [ { id: "a", data: "qwe" }, { id: "b", data: "zxc" }... ]
  },
...
]

我想把它转换成,

const result = {
    0 : {
        a: "abc",
        b: "wxy"
    },
    1 : {
        a: "qwe",
        b: "zxc"
    }
}

到目前为止,我有这个:

  const transforms = array
    .map((o) => {
      return { [o.key]: o.key2 };
    })
    .reduce((prev, curr) => {
      for (let key in curr)
        prev[key] = curr[key]
          .map((c) => {
            return { [c.id]: c.data};
          })
          .reduce((prev, curr) => {
            for (let key in curr) prev[key] = curr[key];
            return prev;
          }, {});

      return prev;
    }, {});

这很难阅读,而且性能可能不是很好。 老实说,我什至不知道它是否真的 100% 有效。 到目前为止,它给了我预期的结果。

我该如何重构它? 请帮忙。

【问题讨论】:

标签: javascript arrays algorithm object


【解决方案1】:

你的任务可以有效地分解为 4 个小问题:

key2.map(({id,data}) => ({[id]:data}))
Object.assign({}, ...key2.map(({id,data}) => ({[id]:data})))
src.map(({key2}) => 
        Object.assign({}, ...key2.map(({id,data}) => ({[id]:data}))))
  • destructure 将结果数组(本质上是一个对象)放入对象中
{...result} = src.map(({key2}) => 
        Object.assign({}, ...key2.map(({id,data}) => ({[id]:data}))))
      

生成的代码更紧凑,works noticeably faster

您可以通过以下方式找到现场演示:

const src = [{key:0,key2:[{id:"a",data:"abc"},{id:"b",data:"wxy"}]},{key:1,key2:[{id:"a",data:"qwe"},{id:"b",data:"zxc"}]}],

      {...result} = src.map(({key2}) => 
        Object.assign({}, ...key2.map(({id,data}) => ({[id]:data}))))
      
console.log(result)
.as-console-wrapper{min-height:100%;}

【讨论】:

    【解决方案2】:

    const array = [
        {
          key: 0,
          key2: [ { id: "a", data: "abc" }, { id: "b", data: "wxy" }]
        },
        {
          key: 1,
          key2: [ { id: "a", data: "qwe" }, { id: "b", data: "zxc" }]
        },
    
    ]
    
    const result = array.reduce((res, entry) => {
        return Object.assign(res, { [entry.key]: entry.key2.reduce((data, current) => {
            return Object.assign(data, { [current.id]: current.data }) 
        }, {}) });
    }, {})
    
    console.log(result)

    转换函数

    array.reduce((res, entry) => {
        return Object.assign(res, { [entry.key]: entry.key2.reduce((data, current) => {
            return Object.assign(data, { [current.id]: current.data }) 
        }, {}) });
    }, {})
    

    【讨论】: