There are multiple ways to perform a deep merge of two JSON objects using ES6. One way is to use the spread operator (...) and recursion. Here is an example function:
function deepMerge(obj1, obj2) {
let result = {...obj1}; // create a copy of obj1
Object.keys(obj2).forEach(key => {
if (result[key] && typeof obj2[key] === 'object') {
result[key] = deepMerge(result[key], obj2[key]); // recursively merge sub-objects
} else {
result[key] = obj2[key]; // otherwise overwrite value
}
});
return result;
}
You can then use this function to merge two JSON objects like this:
const obj1 = {
foo: 'bar',
baz: {
alpha: 'beta'
}
};
const obj2 = {
foo: 'baz',
baz: {
delta: 'gamma'
}
};
const merged = deepMerge(obj1, obj2);
console.log(merged);
// Output: { foo: 'baz', baz: { alpha: 'beta', delta: 'gamma' } }
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-02-06 11:00:00 +0000
Seen: 17 times
Last updated: Feb 14 '22
How can JSON be decoded while using a universal interface as a field?
How can I convert a `dataframe` from Polars to `serde_json::Value` using serialization?
In RobotFramework, can multiple key-value pairs in JSON format be obtained and saved to a JSON file?
How can JSON objects with dynamic keys be extracted in Athena/Presto?
What is the method for parsing a single JSON object in Android?
"What is the method of utilizing CURL POST with a payload in Json format?"
How can a JSON serialize detect a potential object cycle in .NET MAUI?
How can struct be utilized in the Go language to parse nested JSON?