JS和程序设计的新手。我已经在SO和其他资源上尝试了许多解决方案,但似乎无法弄清楚。我有二十个或更多代表用户“投票”的对象。根据用户的输入,它们都有相同的键和不同的值。我需要通过汇总不同的值来“汇总票数”并返回一个对象。
示例:
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
}
{
"Chicago" : "1",
"New York" : "2",
"Seattle" : "3"
}
{
"New York" : "1",
"Chicago" : "2",
"Seattle" : "3"
}
我希望将以上三个对象简化为:
{
"New York" : "6",
"Seattle" : "7",
"Chicago" : "5"
}
如果您能指出正确的方向,我将不胜感激!
答案 0 :(得分:0)
答案 1 :(得分:0)
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)