So as per dictionary compare means
estimate, measure, or note the similarity or dissimilarity between.
When we compare the above two objects it returns true whereas in the snippet code below it will return false.
The reason it returns false is because both are of two different references even though its property’s values are the same. So how do we solve this?
Solution 1 — using JSON.stringify()
here we have used JSON.stringify() method to convert it to JSON string and easy solution but there is a known issue with this approach.
here if you notice emp2 object property id is set at last and while comparing it will return false because the first object will convert it into to string as
and emp2 object will get converted to
so, this is not a foolproof solution.
Solution 2— using Lodash
here I have used a popular library called Lodash which does the hard work for us. I ran a few other tests
and it works perfectly fine for nested objects as well. If you notice in the above example, I have added a property department which is of type object. I wanted to see how it works with array which is also an object.
it worked as well so I tried swapping the items in the array and here is the result
it turned out to be returning false.
Solution 3— using Object.keys
and this is working perfectly well & I tried running few more tests by introducing arrays with complex types instead of simple types like string or number it failed. Incase if you see the above implementation, you might notice I am performing the sort operation on array hence it worked for simple/basic types whereas Lodash might not be performing it hence it returned false.
Even though the Lodash was able to solve multiple issues it turned out to be it is also not a fool proof solution (failed comparison of array). Initially I was wondering how such a popular library failed to work when array was introduced. It seems like we must write our own code to make it work.
Let me know your valuable comments & am I missing something? please let me know.