Skip to content

Instantly share code, notes, and snippets.

@aherve
Created August 30, 2017 14:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aherve/37b1757718500026089e15d071068e68 to your computer and use it in GitHub Desktop.
Save aherve/37b1757718500026089e15d071068e68 to your computer and use it in GitHub Desktop.
// merge an array of objects
const data = [ {a: 1}, {b: 2}, {c: 3} ]
const merged = data.reduce((res, obj) => ({...res, ...obj}), {})
console.log(merged) // => { a: 1, b: 2, c: 3 }
// merge an array of objects by property
const toMerge = [
{ id: 1, value: 'a', },
{ id: 2, value: 'b', },
{ id: 3, value: 'c' },
{ id: 1, score: 1 },
{ id: 2, score: '2' },
]
const mergedByProperty = toMerge.reduce((result, obj) => ({
...result,
[obj.id]: {
...result[obj.id],
...obj
}
}), {})
console.log(mergedByProperty) // =>
/*
*{ '1': { id: 1, value: 'a', score: 1 },
* '2': { id: 2, value: 'b', score: '2' },
* '3': { id: 3, value: 'c' } }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment