使用Javascript / JQuery在JSON对象中的差异 [英] Difference in JSON objects using Javascript/JQuery

查看:80
本文介绍了使用Javascript / JQuery在JSON对象中的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中有两个JSON对象,除了数值之外都是相同的。它看起来像这样:

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

var data = {
  "eth0":{"Tx":"4136675","Rx":"13232319"},
  "eth1":{"Tx":"4","Rx":"0"},
  "lo":{"Tx":"471290","Rx":"471290"}
}

var old = {
  "eth0":{"Tx":"4136575","Rx":"13232219"},
  "eth1":{"Tx":"4","Rx":"0"},
  "lo":{"Tx":"471290","Rx":"471290"}
}

一个名为data的对象具有当前值,另一个名为old的对象从1秒前开始具有相同的值。我想在值中输出只有 change 的JSON对象,这样我就可以计算网络接口上的数据吞吐量。

One object called "data" has the current values, another object called "old" has the same values from 1 second ago. I'd like to output a JSON object with only the change in values so I can calculate data throughput on the network interfaces.

var throughput = {
  "eth0":{"Tx":"100","Rx":"100"},
  "eth1":{"Tx":"0","Rx":"0"},
  "lo":{"Tx":"0","Rx":"0"}
}

我不知道如何遍历JSON数据 - 它可能适用于任意数量的接口。

I'm not sure how to go about traversing the JSON data - it could be for any number of interfaces.

任何人都可以借给我一个手吗?提前致谢

Can anyone please lend me a hand? Thanks in advance

推荐答案

您可以遍历父对象和子对象属性:

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];
      }
    }
  }
}

这篇关于使用Javascript / JQuery在JSON对象中的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆