Magicsheet logo

Deep Merge of Two Objects

Medium
66.2%
Updated 6/1/2025

Asked by 1 Company

Topics

Deep Merge of Two Objects

What is this problem about?

The Deep Merge of Two Objects interview question asks you to implement a function that merges two objects or JSON structures. Unlike a "shallow merge" (which only copies top-level properties), a "deep merge" recursively combines nested objects and arrays. If both objects have the same key, the value from the second object usually overrides the first, unless both are objects/arrays, in which case they should be merged. This Deep Merge of Two Objects coding problem is a test of recursive data structures.

Why is this asked in interviews?

Valve and other companies use this to test a candidate's mastery of Recursion and their understanding of object types. It evaluates if you can handle edge cases like mixing arrays and objects, handling null values, and avoiding infinite loops if circular references exist. It’s a very common utility implementation in modern JavaScript development.

Algorithmic pattern used

This relies on the Recursion and Type Checking pattern.

  1. Base Case: If either input is not an object (or is null), return the second input.
  2. Recursive Step:
    • Iterate through the keys of the second object.
    • If a key exists in both and both values are objects, call deepMerge on them.
    • Otherwise, simply assign the value from the second object to the result.
  3. Array Handling: Decide if arrays should be concatenated, or if elements at the same index should be merged.

Example explanation

obj1 = { a: { b: 1 }, c: 2 }, obj2 = { a: { d: 3 }, e: 4 }

  1. Keys in obj2: a, e.
  2. Process a: obj1.a and obj2.a are both objects. Recurse.
    • obj1.a merged with obj2.a results in { b: 1, d: 3 }.
  3. Process e: Doesn't exist in obj1. Copy obj2.e. Final result: { a: { b: 1, d: 3 }, c: 2, e: 4 }.

Common mistakes candidates make

  • Shallow Copy: Forgetting to recurse, which results in the nested object in obj2 completely replacing the one in obj1.
  • Type mismatch: Not checking if both values are actually objects before recursing (e.g., trying to merge a number with an object).
  • Mutating Inputs: Modifying the original obj1 instead of returning a new merged object.

Interview preparation tip

Be prepared to handle arrays. Some interviewers want arrays to be concatenated, others want them merged by index. Clarify the expected behavior for array conflicts early in the conversation.

Similar Questions