What is the most efficient way to compare two JSON-formatted objects data in node.js?
These objects do not contain "undefined" or functions and their propotype is Object
.
I've heard there is a good support if JSON in node.js
Friends! I'm really sorry if I don't understand something, or explain question in wrong terms. All I wanna do is to compare the equality of two pieces of JSON-standardized data like this:
{"skip":0, "limit":7, "arr": [1682, 439, {"x":2, arr:[]}] }
{"skip":0, "limit":7, "arr": [1682, 450, "a", ["something"] }
I'm 100% sure there will be no functions, Date
, null
or undefined
, etc. in these data. I want to say I don't want to compare JavaScript objects in the most general case (with complex prototypes, circular links and all this stuff). The prototype of these data will be Object
. I'm also sure lots of skillful programmers have answered this question before me.
The main thing I'm missing is that I don't know how to explain my question correctly. Please feel free to edit my post.
My answer:
First way: Unefficient but reliable. You can modify a generic method like this so it does not waste time looking for functions and undefined
. Please note that generic method iterates the objects three times (there are three for .. in
loops inside)
Second way: Efficient but has one restriction. I've found JSON.stringify
is extremely fast in node.js. The fastest solution that works is:
JSON.stringify(data1) == JSON.stringify(data2)
Very important note! As far as I know, neither JavaScript nor JSON don't matter the order of the object fields. However, if you compare strings made of objects, this will matter much. In my program the object fields are always created in the same order, so the code above works. I didn't search in the V8 documentation, but I think we can rely on the fields creation order. In other case, be aware of using this method.
In my concrete case the second way is 10 times more efficient then the first way.
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