Difference in JSON objects using Javascript/JQuery

后端 未结 5 2059
我在风中等你
我在风中等你 2020-11-27 15:50

I have two JSON objects in Javascript, identical except for the numerical values. It looks like this:

var data = {
  \"eth0\":{\"Tx\":\"4136675\",\"Rx\":\"13         


        
相关标签:
5条回答
  • 2020-11-27 15:53

    This did the trick for me when dealing with a similar problem. It gets the differences in second compared to first.

    var first  = originalObj;
    var second = modifiedObj;
    var diff   = {};
    
    var differ = function(first, second, result) {
        var i = 0;
        for (i in first) {
            if (typeof first[i] == "object" && typeof second[i] == "object") {
                result[i] = differ(first[i], second[i], {});
                if (!result[i]) delete result[i];
            } else if (first[i] != second[i]) {
                result[i] = second[i];
            }
        }
        return isEmpty(result) ? undefined : result;
    }
    
    differ(old_conf, new_conf, diff);
    

    Code is a bit of a special case, but you get the general idea :P

    0 讨论(0)
  • 2020-11-27 15:57

    You can use an object traversal module like nervgh/object-traverse to do this.

    var result = {}
    Object.traverse(old, function(node, value, key, path) {
      var resultObject = result
      for(var n=0; n<path.length-1; n++) {
        resultObject = resultObject[path[n]]
      }
      resultObject[key] = value
    });
    
    0 讨论(0)
  • 2020-11-27 16:05

    Maybe it's already answered enough, but let me add my shameless plug :) A JSON (actually any javascript object or array structure) diff & patch library I open sourced at github:

    https://github.com/benjamine/jsondiffpatch

    it generates diffs (also in JSON format, and with a small footprint), which you can use client (check the test page) & server side, and if present, it uses http://code.google.com/p/google-diff-match-patch/ for long strings automatically.

    check the DEMO page to see how it works.

    0 讨论(0)
  • 2020-11-27 16:09

    The basic premise for iterating over objects in JavaScript is like so

    var whatever = {}; // object to iterate over
    for ( var i in whatever )
    {
      if ( whatever.hasOwnProperty( i ) )
      {
         // i is the property/key name
         // whatever[i] is the value at that property
      }
    }
    

    Fixing up a checker wouldn't be too hard. You'll need recursion. I'll leave that as an exercise for you or another SOer.

    0 讨论(0)
  • 2020-11-27 16:16

    You can iterate through the parent and child object properties:

    var diff = {};
    for(var p in data){
      if (old.hasOwnProperty(p) && typeof(data[p]) == 'object'){
        diff[p] = {};
        for(var i in data[p]){
          if (old[p].hasOwnProperty(i)){
            diff[p][i] = data[p][i] - old[p][i];
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题