Is there a way I can do a shallow comparison that will not go down and compare the contents of objects inside of objects in Javascript or lodash? Note that I did check lodash, but it appears to perform a deep comparison which I don't want to do.
var a = { x: 1, y: 2} var b = { x: 1, y: 3}
Is there some way for example to compare a
and b
?
Objects are not like arrays or strings. So simply comparing by using "===" or "==" is not possible. Here to compare we have to first stringify the object and then using equality operators it is possible to compare the objects.
In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.
Hi, a shallow comparison happen if 2 values are equals in case of primitive types (is data that is not an object and has no methods) like: string, number, bigint, boolean, undefined, and symbol. But in case of object it just check the reference and not the values inside that object.
Comparing objects is easy, use === or Object.is(). This function returns true if they have the same reference and false if they do not. Again, let me stress, it is comparing the references to the objects, not the keys and values of the objects. So, from Example 3, Object.is(obj1,obj2); would return false.
Simple ES6 approach:
const shallowCompare = (obj1, obj2) => Object.keys(obj1).length === Object.keys(obj2).length && Object.keys(obj1).every(key => obj1[key] === obj2[key]);
Here I added the object keys amount equality checking for the following comparison should fail (an important case that usually does not taken into the account):
shallowCompare({ x: 1, y: 3}, { x: 1, y: 3, a: 1}); // false
2019 Update. Per Andrew Rasmussen' comment we also need to take into account undefined
case. The problem with the previous approach is that the following comparison returns true
:
({ foo: undefined })['foo'] === ({ bar: undefined })['foo'] // true
So, explicit keys existence check is needed. And it could be done with hasOwnProperty
:
const shallowCompare = (obj1, obj2) => Object.keys(obj1).length === Object.keys(obj2).length && Object.keys(obj1).every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key] );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With