简体   繁体   中英

Reduce Array of Objects with Dynamic Keys

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

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}

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 (ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM