1 | initial version |
One common way to merge two JSON objects deeply in ES6 is to use the spread operator (...) and recursion.
Here is an example function that takes two JSON objects as input and returns a merged object that includes all the properties of both objects, with nested objects being merged as well:
const mergeObjects = (obj1, obj2) => {
const merged = {...obj1};
for (let key in obj2) {
if (typeof obj2[key] === 'object' && obj2[key] !== null) {
merged[key] = mergeObjects(merged[key], obj2[key]);
} else {
merged[key] = obj2[key];
}
}
return merged;
};
Here, the function starts by creating a copy of obj1
using the spread operator. Then, it iterates over all the keys of obj2
. If a key exists in both objects and the value of that key is another object, then the function calls itself recursively to merge those nested objects. Otherwise, it simply copies over the value of the key from obj2
into the merged
object.
In this way, a deeply merged object is created that includes all the properties of both original objects.