根据对象数组中的键创建对象

时间:2019-12-01 04:12:34

标签: javascript arrays lodash

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

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

,我希望结果数组为

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

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

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

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

image

4 个答案:

答案 0 :(得分:2)

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

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))

答案 1 :(得分:2)

使用lodash可以使用_.mergeWith()并在定制程序函数中合并值:

const 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}]
            
const result = _.mergeWith({}, ...arr, (ov = [], sv) => ov.concat(sv))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

答案 2 :(得分:0)

您可以用最简单的方式尝试这种方式。

  

也可以在线访问https://rextester.com/IPI35964来尝试查看输出。

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

var output = {}
for(var obj of arr){
    for(var key in obj){
        if(key in output){
            output[key].push(obj[key])
        } else {
            output [key] = [obj[key]]
        }
    }
}
console.log(output)
  

输出

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

答案 3 :(得分:0)

一种相当干净的方法:

  • 创建一大组键值对
  • 通过键将这些键值对分组
  • 从分组的键值对中提取值

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

// Get one big array of all key-value pairs
var pairs = _.flatMap(arr, _.entries);

// Group by the keys (index 0 of the pairs)
var groups = _.groupBy(pairs, 0);

// Extract the values
var final = _.mapValues(groups, _.partial(_.map, _, 1));

//console.log(pairs);
console.log(final);


// Using chaining:
var final2 = _.chain(arr)
  .flatMap(_.entries)
  .groupBy(0)
  .mapValues(_.partial(_.map, _, 1));

console.log(final2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>