Deep Merge of Two Objects - Problem

Given two JavaScript values obj1 and obj2, return a deep merged value according to these rules:

Objects: If both values are objects, the resulting object should have all keys that exist on either object. If a key belongs to both objects, recursively deep merge the two associated values. Otherwise, add the key-value pair to the resulting object.

Arrays: If both values are arrays, the resulting array should be the same length as the longer array. Apply the same merging logic as objects, but treat the array indices as keys.

Otherwise: The resulting value is obj2 (obj2 takes precedence).

You can assume obj1 and obj2 are the output of JSON.parse().

Input & Output

Example 1 — Object Merging
$ Input: obj1 = {"a": 1, "b": {"x": 2}}, obj2 = {"b": {"y": 3}, "c": 4}
Output: {"a": 1, "b": {"x": 2, "y": 3}, "c": 4}
💡 Note: Key 'a' only in obj1, key 'c' only in obj2, key 'b' exists in both so we recursively merge the nested objects
Example 2 — Array Merging
$ Input: obj1 = [1, 2], obj2 = [3, 4, 5]
Output: [3, 4, 5]
💡 Note: Both arrays merge by index: index 0 gets obj2[0]=3, index 1 gets obj2[1]=4, index 2 only exists in obj2 so gets 5
Example 3 — Mixed Types
$ Input: obj1 = {"a": [1, 2]}, obj2 = {"a": [3, 4, 5], "b": "hello"}
Output: {"a": [3, 4, 5], "b": "hello"}
💡 Note: Objects merge, then arrays at key 'a' merge by index giving [3, 4, 5], key 'b' only in obj2

Constraints

  • obj1 and obj2 are valid JSON values
  • Maximum depth ≤ 1000
  • Objects can have up to 1000 keys
  • Arrays can have up to 1000 elements

Visualization

Tap to expand
Deep Merge: Input → Process → Outputobj1{"a": 1,"b": {"x": 2}}obj2{"b": {"y": 3},"c": 4}Merged Result{"a": 1,"b": {"x": 2, "y": 3},"c": 4}Deep Merge Process:Both objects → merge keys recursively
Understanding the Visualization
1
Input
Two JSON values that may be objects, arrays, or primitives
2
Type Check
Determine merge strategy based on value types
3
Output
Single merged structure following deep merge rules
Key Takeaway
🎯 Key Insight: Recursion naturally handles nested structures by applying the same merge logic at every level
Asked in
Microsoft 35 Google 28 Facebook 22
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen