880. Differences Between Two Objects

Create a method that returns a new object that represents the differences between two deeply nested objects or arrays, obj1 and obj2.

The function should detect any changes by comparing the two objects' characteristics. Only keys with values different from obj1 to obj2 should be included in the returned object.

An array [obj1 value, obj2 value] should be used to describe the value for each modified key. The returned object shouldn't contain keys that are present in one object but absent from the other. A highly nested object with a difference array for each leaf value should be the end product.

The arrays' indices are regarded as their keys when comparing two arrays.  

You may assume that both objects are the output of JSON.parse.

Example 1:

Input :

obj1 = {

 "a": 1,

 "v": 3,

 "x": [],

 "z": {

  "a": null

 }

}

obj2 = {

 "a": 2,

 "v": 4,

 "x": [],

 "z": {

  "a": 2

 }

}

Output : 

{

 "a": [1, 2],

 "v": [3, 4],

 "z": {

  "a": [null, 2]

 }

}

Explanation :

The keys "a", "v", and "z" all had changes applied. "a" was changed from 1 to 2. "v" was changed from 3 to 4. "z" had a change applied to a child object. "z.a" was changed from null to 2.

Example 2:

Input :

obj1 = {

 "a": 5, 

 "v": 6, 

 "z": [1, 2, 4, [2, 5, 7]]

}

obj2 = {

 "a": 5, 

 "v": 7, 

 "z": [1, 2, 3, [1]]

}

Output : 

{

 "v": [6, 7],

 "z": {

  "2": [4, 3],

  "3": {

   "0": [2, 1]

  }

 }

}

Explanation :

In obj1 and obj2, the keys "v" and "z" have different assigned values. "a" is ignored because the value is unchanged. In the key "z", there is a nested array. Arrays are treated like objects where the indices are keys. There were two alterations to the the array: z[2] and z[3][0]. z[0] and z[1] were unchanged and thus not included. z[3][1] and z[3][2] were removed and thus not included.

Now Your Turn!

Pick the correct output for the given input

Input : 

obj1 = {

 "a": [1, 2, {}], 

 "b": false

}

obj2 = {  

 "b": false,

 "a": [1, 2, {}]

}

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 objects or arrays
  • 2 <= JSON.stringify(obj1).length <= 105
  • 2 <= JSON.stringify(obj2).length <= 105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

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

Input:

Obj1
Obj2