DEV Community

Cover image for Compare objects in JS

Compare objects in JS

Gajender Tyagi on September 12, 2021

How can you compare to objects with same properties cause we know both the objects all though same values but sits at different memory location he...
Collapse
 
talorlanczyk profile image
TalOrlanczyk

Nice way but small problem with it is if the object aren’t order the same way you gonna get false
Unlike lodash isEqual that check for the key itself
You can check if object are similar by go our there keys and if you dont find something it not equal

Collapse
 
nbilyk profile image
Nicholas Bilyk

Agreed, one should use a utility like lodash or underscore for this. Or write your own recursive function and use Object.keys.

To expand on what I believe Tal means regarding ordering --
An object's keys are ordered in the same order they were inserted (unless the keys look like numbers, in which case they're ascending)
Therefore:
JSON.stringify({a:1,b:2}) == JSON.stringify({b:2,a:1}) // false

Collapse
 
talorlanczyk profile image
TalOrlanczyk

ya thanks you very much

Collapse
 
ankittanna profile image
Ankit Tanna

I disagree. I wouldn't want to import a library to check such small thing. I can write a small function that recursively iterates and compares values of the properties.

Thread Thread
 
talorlanczyk profile image
TalOrlanczyk

Ya it depend if you use but the main concepts here its to use something more reliable then json strigify
And lodash is pretty small library

Collapse
 
halbano profile image
halbano

Agree, but partially. An object is not a data structure in which an order is defined, right? Not sure if that would be a concern when comparing JSON objects.

Collapse
 
ankittanna profile image
Ankit Tanna

Not a reliable method bro! also if the json is too huge, the good bye performance!

Collapse
 
sagartyagi121 profile image
Gajender Tyagi

Yup you are right this is just for fun question not to be used in production 😜

Collapse
 
ziv profile image
zivka

Notice that by using JSON.stringify the order of the fields matter…

Collapse
 
sagartyagi121 profile image
Gajender Tyagi

Yup it does

Collapse
 
jankapunkt profile image
Jan Küster 🔥

Stringify is useless without replacer and reviver to compare objects.

Collapse
 
sagartyagi121 profile image
Gajender Tyagi

As you all can see in the end I have a stackoverflow link so refer that for similar discussion with some solutions as well.