Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a shallow comparison of the properties of two objects with Javascript or lodash?

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?

like image 597
Samantha J T Star Avatar asked Mar 08 '14 08:03

Samantha J T Star


People also ask

How can we compare two objects in JavaScript?

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.

How do you compare two objects with Lodash?

In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.

What is shallow compare objects JavaScript?

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.

What is the best way to compare objects in JavaScript?

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.


1 Answers

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]   ); 
like image 136
dhilt Avatar answered Oct 01 '22 23:10

dhilt