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))
Top comments (6)
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.
Thank you Alex
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.
OP said merge, not clone. Also when stringify-parse'd, non-JSON primitives are goner. Though, indeed a solution is to use YAML.
Thank you Dorgan,
Please read my previous articles about Meioisis and Mergerino
Regards