Get the property of the difference between two obj

2020-02-26 12:29发布

Let's say that I have an object which looks like this:

{
  prop1: false,
  prop2: false,
  prop3: false
}

and another object which looks like this:

{
  prop1: false,
  prop2: true,
  prop3: false
}

where the difference is within the prop2 property. Is there any way or library (vanilla preferred though) which will compare the two objects, find the property with the different value, and return the property name (in this case prop2)?

I have tried using the difference and differenceBy functions in lodash to no success. Any help or suggestions will be greatly appreciated!

2条回答
戒情不戒烟
2楼-- · 2020-02-26 12:52

this is the fastest and simplest method

var a ={
  prop1: false,
  prop2: false,
  prop3: false
}

var b={
  prop1: false,
  prop2: true,
  prop3: false
}

 JSON.stringify(a) === JSON.stringify(b) 

this return false. order of props is also important

查看更多
Viruses.
3楼-- · 2020-02-26 13:03

You could filter the keys (assuming same keys) by checking the unequal value.

var obj1 = { prop1: false, prop2: false, prop3: false },
    obj2 = { prop1: false, prop2: true, prop3: false },
    difference = Object.keys(obj1).filter(k => obj1[k] !== obj2[k]);
    
console.log(difference);

查看更多
登录 后发表回答