DEV Community 👩‍💻👨‍💻

artydev
artydev

Posted on

Deep merge Objects in Javascript with Mergerino

To merge objects in JS, you can use Object.assign.
The problem with is that it only accomplishes 'shallow merge'.

It does not take in account nested properties.

In my scripts I use Mergerino to get things done.

You can test it here : Merge

const merge = mergerino

const user = {
  name: 'David',
  phone: 122345678,
  location: {
    city: 'Camden',
    country: 'UK'
  }
};
const updates = {
  location: {
    city: 'Smithfield'
  }
};
console.log(Object.assign({}, user, updates));

console.log(merge(user, updates))
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
lexlohr profile image
Alex Lohr

This use case is always a bit difficult when it comes to arrays: should they be extended or overwritten? Mergerino treats arrays as objects and therefore will overwrite values at their keys. This might not be what you expect, so be careful about your use case.

Collapse
artydev profile image
artydev Author

Thank you Alex

Collapse
patarapolw profile image
Pacharapol Withayasakpunt • Edited on

It is as easy as recursive function. However, what you mean by merging, when there is conflict varies.

I usually have to write merge function, because I cannot trust third party libraries on how they resolve conflicts. Not even lodash.

Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
patarapolw profile image
Pacharapol Withayasakpunt

OP said merge, not clone. Also when stringify-parse'd, non-JSON primitives are goner. Though, indeed a solution is to use YAML.

Collapse
artydev profile image
artydev Author

Thank you Dorgan,

Please read my previous articles about Meioisis and Mergerino

Regards

DEV runs on 100% open source code known as Forem.

 
Contribute to the codebase or host your own.
 
Check these out! 👇