Skip to content

Instantly share code, notes, and snippets.

@bendc
Created July 21, 2016 14:15
Show Gist options
  • Save bendc/1726e1ad49723d7df1d0dc09bd560421 to your computer and use it in GitHub Desktop.
Save bendc/1726e1ad49723d7df1d0dc09bd560421 to your computer and use it in GitHub Desktop.
Deep merge of JSON-like objects
const merge = (() => {
const duplicate = object => JSON.parse(JSON.stringify(object));
return (...objects) => Object.assign(...objects.map(duplicate));
})();
@bendc
Copy link
Author

bendc commented Jul 21, 2016

// comparison with Object.assign

const foo = { a: [1] };
const bar = { b: [2] };

const merged = merge(foo, bar);
const assigned = Object.assign({}, foo, bar);

bar.b.push(3);

console.log(merged.b);   // => [2]
console.log(assigned.b); // => [2, 3]

@cuth
Copy link

cuth commented Jul 21, 2016

Does this count as a JSON-like object?

const merged = merge({ a: { a1: true }}, { a: { a2: true }});

console.log(merged); // => { a: { a2: true }}

Wouldn't we want: { a: { a1: true, a2: true }}?

@bendc
Copy link
Author

bendc commented Jul 21, 2016

@cuth I think both results could be reasonable. I personally prefer the behavior of Object.assign (i.e. the last one wins) as it lets you easily override previous properties (useful for example when dealing with state objects).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment