简体   繁体   中英

How to compare JavaScript objects obtained by parsing JSON?

wtf1 = JSON.parse('{"asdf": "jkl"}');
wtf2 = JSON.parse('{"asdf": "jkl"}');

wtf1 == wtf2; // false
wtf1 === wtf2; // false

I've recently stumbled upon the above problem. This counter-intuitive situation makes it hard to, for example, find a specific object in an array deep in a JSON hierarchy.

Any way to somehow compare such objects?

For simple objects you can stringify them again (with ordered keys) and compare strings. For example:

 var wtf1 = JSON.parse('{"a": "a", "b": "b"}'); var wtf2 = JSON.parse('{"b": "b", "a": "a"}'); var s1 = JSON.stringify(wtf1, Object.keys(wtf1).sort()); var s2 = JSON.stringify(wtf2, Object.keys(wtf2).sort()); console.log('wtf1 is equal to wtf2: ', (s1 == s2)); 

For nested objects with prototypes etc you should probably use _.isEqual or any other lib that provides deep equality test.

Note, that in general it's not trivial to correctly implement deep equality test for objects, it's not as simple as iterating and comparing keys/values. However, since the "objects were obtained by parsing JSON" you can skip most of complications and recursively stringify nested values.

I think it's better to just compare them before you parse into objects. But this only works if they are exactly the same, including the order of the properties

 var obj1 = {name: "potato", age: 10} var obj2 = {name: "potato", age: 10} console.log(obj1 == obj2) //false console.log(JSON.stringify(obj1) == JSON.stringify(obj2)) //true var obj1 = {name: "potato", age: 10} var obj2 = {age: 10, name: "potato"} console.log(obj1 == obj2) //false console.log(JSON.stringify(obj1) == JSON.stringify(obj2)) //also false 

You cannot compare objects ( as theyre differnet ), but you can iterate over each property, and compare them (and recursively check if theyre objects again):

function compare(obj1,obj2){
   //check for obj2 overlapping props
   if(!Object.keys(obj2).every(key=>obj1.hasOwnProperty(key))){
      return false;
   }

   //check every key for being same
   return Object.keys(obj1).every(function(key){

      //if object
      if((typeof obj1[key]=="object" )&&( typeof obj2[key]=="object")){

          //recursively check
          return compare(obj1[key],obj2[key]);
      }else{

          //do the normal compare
          return obj1[key]===obj2[key];
      }
   });
}

http://jsbin.com/zagecigawi/edit?js

Two objects in JS even with same properties are never equal. You can stringify objects and compare those strings or iterate over all properties (but it's hard if you need deep compare)

you can use loadash for the same. using _.isEqual("object1", "object2");

 var obj1 = {"prop1" : 2, "prop2" : 3 }; var obj2 = {"prop1" : 2, "prop2" : 3}; console.dir(_.isEqual(obj1, obj2)) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> 

Second approach would be JSON.stringify(obj1) === JSON.stringify(obj2)

I recommend using a library implementation for Object equality checking. Try the lodash version .

var object = { 'a': 1 };
var other = { 'a': 1 };

_.isEqual(object, other);
// => true

This will compare JSON structure of response and model(It will compare keys only and not values & will work for any hierarchy)

function compareObjects(response, model) {

    if (response == "" && model == "") {
        return false;
    }

    if (typeof (response) != "object" && typeof (model) != "object") {
        var response = JSON.parse(response);
        var model = JSON.parse(model);
    }

    if (typeof (response) != typeof (model)) {
        return false;
    } else {
        switch (Object.prototype.toString.call(model)) {
            case '[object]':
                var x;
                var mKeys = Object.keys(model);
                for (x in mKeys) {
                    return compareObjects(Object.keys(model)[x], Object.keys(response)[x]);
                }
                break;

            case '[object Array]':
                return compareObjects(model[0], response[0]);

            case "[object String]":
                return model == response;

            default:
                return true;
        }
    }
}
var response = '[{"educationId":5,"degreeName":"Bacheltecture - B.Arch"},{"educationId":2,"degreeName":"Bachelor of Arts - B.A. "},{"educationId":3,"degreeName":"Bachelor of Ayurvedic Medicine  Surgery - B.A.M.S. "}]';
var model = '[{"degreeName":null},{"educationId":null,"degreeName":null},{"educationId":null,"degreeName":null}]';

var output = compareObjects(response, model);

console.log(output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM