将具有嵌套对象数组的对象数组转换为类似数组的对象

时间:2020-07-07 08:09:31

标签: javascript arrays algorithm object

对不起,标题。我什至不知道该如何解释自己想要的东西。

这就是我要实现的目标

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%有效。 到目前为止,它给了我预期的结果。

我该如何重构? 请帮忙。

2 个答案:

答案 0 :(得分:4)

您的任务可以有效地分解为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%;}

答案 1 :(得分:0)

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 }) 
    }, {}) });
}, {})