简体   繁体   中英

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. I've tried numerous solutions on SO and other resources and cannot seem to figure this out. 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:

 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) 

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