Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the equality of JSON-formatted objects in node.js

Tags:

json

node.js

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

like image 662
Dan Avatar asked Mar 23 '12 21:03

Dan


1 Answers

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.

like image 101
Dan Avatar answered Sep 29 '22 09:09

Dan