📜 ⬆️ ⬇️

JSonCmp - we compare in JavaScript correctly

Here is a JavaScript object serialized in JSon:

var source1 = '[{"vConfig":{"vType":"objectview","serverItemType":"TrackerObject"}}]'; 


And here is another JavaScript object, also serialized in JSon:
')
 var source2 = '[{"vConfig":{"serverItemType":"TrackerObject","vType":"objectview"}}]'; 


They have the same structure, the same parameters, the same values ​​in these parameters. By all indications, both in source1 and in source2 we have the same thing .

But the JavaScript interpreter with us, of course, does not agree. And he quite reasonably believes that source1 and source2 are different lines. And if we deserialize them back, we get two objects, which are located at different memory addresses and ... are also not equal to each other.

And if you, in addition, work with Ext.js, generously generate your classes and do not forget about jSon, then you can reach a total eclipse. How to compare these huge sheets of information about controls that are collected in JSons? Or to sort out tree-like objects, where some other subfields have already been created in each field?

Only one way out - you need to find a way to compare not by value, not by cell in memory, but more flexibly. The objects with the same fields containing the same values should be considered equal . From this point of view, our source1 definitely equal to source2 .

This is how the next bike was born - JSonCmp . A simple, and very necessary function for comparing objects in JavaScript. Of course, I found many attempts to write one, but each of the implementations solved only part of the problem - in the end I put all the interesting ideas into one, adding a couple of my own along the way ...

Using it is easy - just connect jsoncmp.js , and then call:

 jSonCom(object1, object2); 


If objects contain the same information, the function returns true. Else, false.

Ext.js users can use the same algorithm, but in a plug-in wrapper - jsoncmp.ext.js . The code will look like this:

 Ext.ux.util.Object(object1, object2); 


Comparison rules are:


I hope that this is a small and probably imperfect function a little bit, but it will simplify your work.

Source: https://habr.com/ru/post/174091/


All Articles