DEV Community

Discussion on: Compare objects in JS

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
fjones profile image
FJones • Edited on

Iterating over keys has the problem that nested objects need to be considered recursively. The JSON-comparison is also fairly expensive, however.

Collapse
talorlanczyk profile image
TalOrlanczyk

so you can add if your or an object because check with JSON.stringify means if it's not order exactly the same it false

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.

Thread Thread
nbilyk profile image
Nicholas Bilyk

" An object is not a data structure in which an order is defined, right?"
Yes and no. An object (any js object) has a list of keys that does have an explicit order. That order is first if the key can parse to a number, then the keys are ordered ascendingly, and then if the key cannot parse to a number, then the keys are sorted in the order they're inserted.
This is pretty specific to ecmascript/javascript, other languages have different rules for dynamic maps. In all languages however when creating equality rules for dynamic map-like structures, order isn't expected to matter for comparison. (Which is why stringify is the wrong choice for object comparison)

Example:

JSON.stringify({ '3': 'a', 'foo': 'd', '2': 'b', 'bar': 'e', '1': 'c' }) 

Becomes: {"1":"c","2":"b","3":"a","foo":"d","bar":"e"}
Enter fullscreen mode Exit fullscreen mode

Because those keys do have an order, if you used stringify as your comparison, {a: 1, b: 2} which you would expect to equal {b: 2, a: 1}, does not.