[英]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
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"
}
如果您能指出正確的方向,我將不勝感激!
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);
另一個帶有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.