I’d like to merge two objects together, but in a way that preserves children at any depth.
For example:
const base = {
a: {
i: {
foo: true
}
}
};
const add = {
a: {
j: {
foo: false
}
},
b: true
};
const result = {...base, ...add};
console.log(result);
Printed result:
{
a: {
j: {
foo: false
}
},
b: true
}
Ideally, the result would be
{
a: {
i: {
foo: true
}
j: {
foo: false
}
},
b: true
}
Is there a way to… I’m gonna call it "zipper merge" the two objects?
This is for a redux data reducer. I’m going to use null (or a different reducer) to delete if I need to.
3
Answers
You could define a function that recursively merges any number of objects like so:
Lodash has such a function.
This is the deep merge function I use for redux in my applications. For most use cases, merging arrays doesn’t make sense. So my merge fn overwrites when the incoming value is an array