Sometimes, we want to merge 2 JavaScript objects, populating the properties in one if they don’t exist in the other.
In this article, we’ll look at how to merge 2 JavaScript objects, populating the properties in one if they don’t exist in the other.
How to merge 2 JavaScript objects, populating the properties in one if they don’t exist in the other?
To merge 2 JavaScript objects, populating the properties in one if they don’t exist in the other, we can use some object methods.
For instance, we write:
const a = {
'foo': 'bar',
'baz': 'bat'
};
const b = {
'foo': 'quux'
};
const entries = Object.entries(a).filter(([key]) => Object.keys(a).includes(key))
const filteredA = Object.fromEntries(entries)
const c = {
...b,
...filteredA
}
console.log(c)
to make a copy of b
and merge the properties that aren’t in b
into a
and assign the merged object to c
.
To do this, we call Object.enttries
with a
to return a nested array with all the key-value pairs.
Then we call filter
on the returned array with a callback that returns an array of key-value pairs that are only in a
.
Next, we call Object.fromEntries
to converted the nested key-value pair array back to an object.
Finally, we merge b
and filteredA
into c
.
Therefore, c
is:
{
baz: "bat",
foo: "bar"
}
Conclusion
To merge 2 JavaScript objects, populating the properties in one if they don’t exist in the other, we can use some object methods.