jQuery/JavaScript JSON object comparison

后端 未结 5 1419
执笔经年
执笔经年 2020-12-10 06:08

Is it possible to compare 2 sets of json objects for a difference? What I have is a script thats polling for JSON object via jquery $post(). What I want to do is take the ob

5条回答
  •  长情又很酷
    2020-12-10 06:46

    var objectsAreEqual = function(obj1, x){
      var MAX_DEPTH = 10;
      var testEq = function(obj1, x, depth){
        if(depth < MAX_DEPTH){
          for (var p in obj1) {
              if(typeof(obj1[p]) !== typeof(x[p])) return false;
              if((obj1[p]===null) !== (x[p]===null)) return false;
              switch (typeof(obj1[p])) {
                  case 'undefined':
                      if (typeof(x[p]) != 'undefined') return false;
                      break;
                  case 'object':
                      if(obj1[p]!==null && x[p]!==null && (obj1[p].constructor.toString() !== x[p].constructor.toString() || !testEq(obj1[p], x[p], depth + 1))) return false;
                      break;
                  case 'function':
                      if (p != 'equals' && obj1[p].toString() != x[p].toString()) return false;
                      break;
                  default:
                      if (obj1[p] !== x[p]) return false;
              }
          }
        }
        return true;
      };
      // this is a little ugly, but the algorithm above fails the following: testEq([[1,2],[]], [[1,2],[1,3]], 0)
      return testEq(obj1, x, 0) && testEq(x, obj1, 0); 
    
    };
    

提交回复
热议问题