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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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,nullorundefined, 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 beObject. 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 threefor .. inloops inside)Second way: Efficient but has one restriction. I’ve found
JSON.stringifyis 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.