根据对象数组中的键创建对象 [英] Create an object based on the keys in array of objects

查看:83
本文介绍了根据对象数组中的键创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想根据它们的键创建另一个对象.例如我有一个数组

I am having an array of objects and I want to create another object based on their keys. For example I am having an array as

var arr = [{1: 36011, 2: 18320, 3: 36011, 4: 10570},
            {1: 19754, 2: 6722, 3: 19754, 4: 6699},
            {1: 15711, 2: 10039, 3: 15711, 4: 4172}]

,我希望我的结果数组为

and I want my result array as

var result = {1:[36011,19754,15711], 2:[18320,6722,10039],..}

建议我使用lodash,我是新手,所以我尝试使用reduce

I was suggested to use lodash, I am new to this so I've tried using reduce

var i = 1, new_arr = {};
_.reduce(arr, function(key, val){
     new_arr[i++] = temp1.key 
return new_arr;
},{})

我得到的值为 undefined .有什么问题,有人可以帮我吗?

I am getting the values as undefined. What is the mistake, Can anyone help me with this?

推荐答案

乍一看,这似乎令人生畏.从空对象开始减少数据集.然后从外部reduce的结果开始减少每一行,并以到目前为止的结果为基础.

This might look intimidating at first. Start reducing the dataset from an empty object. Then reduce each row starting with result of outer reduce and build on the result so far.

const addToBucket = (bucket = {}, k, v, prev = bucket[k] || []) => ({
  ...bucket,
  [k]: [...prev, v],
})

const toBucket = list =>
  list.reduce(
    (bucket, row) =>
      Object.entries(row).reduce((b, [k, v]) => addToBucket(b, k, v), bucket),
    {},
  )

const data = [
  { 1: 36011, 2: 18320, 3: 36011, 4: 10570 },
  { 1: 19754, 2: 6722, 3: 19754, 4: 6699 },
  { 1: 15711, 2: 10039, 3: 15711, 4: 4172 },
]

console.log(toBucket(data))

// Nested list, as requested
console.log(Object.entries(toBucket(data)).map(([_, v]) => v))

这篇关于根据对象数组中的键创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆