javascriptintermediate15 minutes

Build a Deep Object Merger Function in JavaScript

Create a function that deeply merges two JavaScript objects, combining nested properties without overwriting entire sub-objects.

Challenge prompt

Write a function named `deepMerge` that accepts two objects and returns a new object by deeply merging them. For any matching keys where the values are both objects, the merge should happen recursively. For other value types, the value from the second object should overwrite the first. Arrays should be replaced entirely by the second object's value. The function should not modify the original input objects.

Guidance

  • Use recursion to handle nested objects.
  • Check if a value is an object before merging deeper.
  • Avoid mutating the input objects; create new objects during merge.

Hints

  • You can use `typeof` and `Array.isArray()` to differentiate between objects and arrays.
  • Use `Object.keys()` to iterate through properties of objects.
  • Remember to create new objects instead of modifying existing ones to preserve immutability.

Starter code

function deepMerge(obj1, obj2) {
  // Your code here
}

Expected output

deepMerge({a: 1, b: {x: 1, y: 2}}, {b: {y: 3, z: 4}, c: 5}) // returns {a: 1, b: {x: 1, y: 3, z: 4}, c: 5}

Core concepts

recursionobject manipulationimmutability

Challenge a Friend

Send this duel to someone else and see if they can solve it.