Difference in JSON objects using Javascript/JQuery

后端 未结 5 2099
我在风中等你
我在风中等你 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

提交回复
热议问题