Build an Immutable Deep Merge Function for Nested JavaScript Objects
Create a robust JavaScript function that performs a deep merge of two objects without mutating either input. The function should recursively merge nested objects and arrays, handling conflicts by favoring values from the second object while preserving original nested structures.
Challenge prompt
Write a function named 'deepMerge' that takes two arguments, both objects, and returns a new object that deeply merges the properties of the two. The merge should be recursive: for any common keys with object values, merge those sub-objects as well. For arrays, concatenate the arrays. Primitive values in the second object overwrite those in the first. Neither of the input objects should be mutated during this process.
Guidance
- • Use recursion to handle nested objects and arrays during the merge.
- • Create and return a new object for the merged result to ensure immutability.
- • Ensure array values are concatenated instead of overwritten.
- • Handle edge cases such as null values and non-object types properly.
Hints
- • Check if a property is an array using Array.isArray() and merge accordingly.
- • Use typeof to differentiate between primitives and objects but be cautious with null (which typeof reports as 'object').
- • Utilize Object.keys or Object.entries for iterating over object properties.
Starter code
function deepMerge(obj1, obj2) {
// Implement your deep merge logic here
}Expected output
const a = { x: 1, y: { z: [1, 2] }, w: 'hello' }; const b = { y: { z: [3], q: 4 }, w: 'world', v: true }; console.log(deepMerge(a, b)); // Expected output: // { x: 1, y: { z: [1, 2, 3], q: 4 }, w: 'world', v: true }
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.