Created
August 30, 2017 14:26
-
-
Save aherve/37b1757718500026089e15d071068e68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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