[英]I need to merge objects. They all have the same keys but differing numerical values. I need to get the sum of values for each key
New to JS and programming in general. JS和一般编程新手。 I've tried numerous solutions on SO and other resources and cannot seem to figure this out.
我已经在SO和其他资源上尝试了许多解决方案,但似乎无法弄清楚。 I have twenty or more objects representing user 'votes'.
我有二十个或更多代表用户“投票”的对象。 The all have the same keys and different values depending on the user input.
根据用户的输入,它们都有相同的键和不同的值。 I need to 'tally the votes' by summing the different values and return a single object.
我需要通过合计不同的值来“汇总选票”并返回一个对象。
Example: 例:
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
}
{
"Chicago" : "1",
"New York" : "2",
"Seattle" : "3"
}
{
"New York" : "1",
"Chicago" : "2",
"Seattle" : "3"
}
I'd like the three objects above to be distilled to this: 我希望将以上三个对象简化为:
{
"New York" : "6",
"Seattle" : "7",
"Chicago" : "5"
}
If you could point me in the right direction I'd greatly appreciate it! 如果您能指出正确的方向,我将不胜感激!
Assuming your votes are in an array, you can reduce it into a single object: 假设您的投票在一个数组中,则可以将其简化为一个对象:
const votes = [ { "Seattle" : "1", "Chicago" : "2", "New York" : "3" }, { "Chicago" : "1", "New York" : "2", "Seattle" : "3" }, { "New York" : "1", "Chicago" : "2", "Seattle" : "3" } ]; const tally = votes.reduce((a, e) => { for (const p in e) { a[p] = a[p] + (+e[p]) || +e[p]; } return a; }, {}) console.log(tally);
Another option with reduce/keys/map
which somewhat more functional
looking: 另一个带有
reduce/keys/map
选项看起来更functional
:
const objs = [{ "Seattle": "1", "Chicago": "2", "New York": "3" }, { "Chicago": "1", "New York": "2", "Seattle": "3" }, { "New York": "1", "Chicago": "2", "Seattle": "3" } ] var result = objs.reduce((r, c) => Object.keys(r).map((x) => r[x] = +r[x] + (+c[x])) && r) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.