使用动态键减少对象数组 [英] Reduce Array of Objects with Dynamic Keys

查看:35
本文介绍了使用动态键减少对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来应该很简单,但我的搜索没有结果.

This seems like it should be pretty simple but my searching hasn't turned anything up.

我有一个看起来像这样的对象数组:

I have an array of objects that looks like this:

[{"A":4,"B":2},{"A":2,"B":1},{"A":3,"B":1},{"A":2,"B":1,"C":1}]

我想把它压缩成看起来像这样的东西(我认为是一个 reduce 函数):

I want to flatten it down to something that looks like this (what I would think of as a reduce function):

{"A": 11, "B": 5, "C": 1}

对象的起始数组是一个更大、更复杂的起始对象转换的产物.重要的细节是键本身是任意值(即您可能会看到D"和E",但代码本身需要对此视而不见).我已经使用 Underscore.js 达到了这一点,我希望找到类似的简洁、功能风格的解决方案.

The starting array of objects is the product of the transformation of a much larger and more complex starting object. The important detail is that the keys themselves are of arbitrary values (i.e. you might see 'D's and 'E's but the code itself needs to be blind to this). I've gotten to this point using Underscore.js and I'm hoping to find similarly clean, functional-style solution.

推荐答案

获取键/值对并更新总和.

Get the key/value pairs and update the sum.

var data = [{ A: 4, B: 2 }, { A: 2, B: 1 }, { A: 3, B: 1 }, { A: 2, B: 1, C: 1 }],
    result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});

console.log(result);

这篇关于使用动态键减少对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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