Use a recursive approach to merge nested objects in JavaScript. You have to use reduce()method for this approach.
Merge nested objects JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
function merge(a, b) {
return Object.entries(b).reduce((o, [k, v]) => {
o[k] = v && typeof v === 'object'
? merge(o[k] = o[k] || (Array.isArray(v) ? [] : {}), v)
: v;
return o;
}, a);
}
let target = { "key1": { "id": 1 }, "key2": { "id": 1, "key": "value" } }
let source = { "key2": { "id": 2 } }
console.log([{}, target, source].reduce(merge));
</script>
</body>
</html>
Output:

Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.