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 of Two Objects INPUT obj1: { "a": 1, "b": {"x": 2} } obj2: { "b": {"y": 3}, "c": 4 } Shared key: "b" Needs merge! ALGORITHM STEPS 1 Check Types Both are objects? Yes - continue merge 2 Collect All Keys ["a", "b", "c"] 3 Process Each Key "a": only in obj1 --> 1 "c": only in obj2 --> 4 4 Recursive Merge "b" {"x":2} + {"y":3} x: 2 + y: 3 = {"x":2,"y":3} FINAL RESULT { "a": 1, "b": { "x": 2, "y": 3 }, "c": 4 } OK - Merged! Key Sources: "a" "b" "c" obj1 both obj2 Key Insight: Deep merge recursively combines nested objects. For shared keys containing objects, the algorithm calls itself to merge at each level. For primitives or type mismatches, obj2 values take precedence. Arrays merge by index, with the longer array determining the final length. TutorialsPoint - Deep Merge of Two Objects | Optimal Solution
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