N个对象如何合并成数组?

新手上路,请多包涵
const obj = {
    'aa':{
        a:1,
        b:2,
        c:3,
        d:4,
        e:5
    },
    'bb':{
        a:1,
        b:2,
        c:3,
        d:4,
        e:5
    },
    'cc':{
        a:1,
        b:2,
        c:3,
        d:4,
        e:5
    }
}

如何转换成类似于

const arr = [
    [1,1,1,1],
    [2,2,2,2],
    [3,3,3,3],
    [4,4,4,4],
    [5,5,5,5]
]

这种结构

阅读 2.2k
2 个回答

如果只是2层结构,可以用下面的代码

let res = []
for (let [key1, value1] of Object.entries(obj)) {
  let arr = []
  for (let [key2, value2] of Object.entries(value1)) {
      arr.push(value2)
  }
  res.push(arr)
}

如果是不知道多成,那就需要封装下,然后用递归的方式去实现

function translateDate (obj) {
return Object.values(obj).reduce((temp,item) => {

    Object.keys(item).forEach(key=>{
        temp[key] = [...(temp[key] || []), item[key]] 
    })
    return temp
}, {})

}
translateDate(obj)
/* {

a:   [1, 1, 1]
b:   [2, 2, 2]
c:   [3, 3, 3]
d:   [4, 4, 4]
e:   [5, 5, 5]

}
*/

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题