872. Deep Merge of Two Objects

Given two values obj1 and obj2, return a deepmerged value.

Values should be deepmerged according to these rules:

  • The resultant object should contain every key found on either of the two values if they are objects. If a key is present in both objects, deepmerge the two values that are related. Add the key-value pair to the final object if not.
  • The resulting array should have the same length as the longer array if the two values are arrays. Treat the indices as keys and use the same reasoning as you would with objects.
  • Otherwise the resulting value is obj2.

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

Example 1:

Input : obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2}

Output : {"a": 2, "c": 3, "b": 2}

Explanation:

The value of obj1["a"] changed to 2 because if both objects have the same key and their value is not an array or object then we change the obj1 value to the obj2 value. Key "b" with value was added to obj1 as it doesn't exist in obj1. 

Example 2:

Input :  obj1 = {"a": 1, "b": {"c": [1 , [2, 7], 5], "d": 2}},  obj2 = {"a": 1, "b": {"c": [6, [6], [9]], "e": 3}}

Output : {"a": 1, "b": {"c": [6, [6, 7], [9]], "d": 2, "e": 3}}

Explanation : 

Arrays obj1["b"]["c"] and obj2["b"]["c"] have been merged in way that obj2 values overwrite obj1 values deeply only if they are not arrays or objects.

obj2["b"]["c"] has key "e" that obj1 doesn't have so it's added to obj1.

Now Your Turn!

Pick the correct output for the given input

Input : obj1 = {"a": 5, "words": ["1", "bye"], "b": true}, obj2 = {"a": 7, "words": [1, 2, 3, 4], "b": false}

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • obj1 and obj2 are valid JSON values
  • 1 <= JSON.stringify(obj1).length <= 5 * 105
  • 1 <= JSON.stringify(obj2).length <= 5 * 105

Fun Facts

0
class Solution{
deepMerge(obj1, obj2) {
//your code goes here
};
}
Test Case

Input:

Obj1
Obj2