javascriptintermediate15 minutes
Create a Deep Object Merge Function
Build a JavaScript function that takes two objects and merges them deeply, combining nested objects instead of overwriting them.
Challenge prompt
Write a function called `deepMerge` that takes two objects as arguments and returns a new object that is a deep merge of the two. If both objects share the same key and their values are objects themselves, merge those objects recursively. For other types of values, the value from the second object should overwrite the first. Your function should not mutate the original input objects.
Guidance
- • Check if a value is an object before recursively merging.
- • Use a helper function or recursion to process nested objects.
- • Avoid mutating the original objects; always create new objects during merging.
Hints
- • Use `typeof` and `Array.isArray` checks to distinguish objects from other types and arrays.
- • Remember that arrays should be overwritten, not deeply merged.
- • Spread syntax (`{...obj}`) can help create shallow copies for immutability.
Starter code
function deepMerge(obj1, obj2) {
// Your code here
}Expected output
deepMerge({a: 1, b: {x: 2}}, {b: {y: 3}, c: 4}) // returns {a: 1, b: {x: 2, y: 3}, c: 4}
Core concepts
recursionobject manipulationimmutability
Challenge a Friend
Send this duel to someone else and see if they can solve it.