我在Javascript中有两个JSON对象,除了数值相同。看起来像这样:
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"} }
一个名为“数据”的对象具有当前值,另一个名为“旧”的对象具有1秒钟前的相同值。我想只输出值的 变化 来输出JSON对象,以便我可以计算网络接口上的数据吞吐量。
var throughput = { "eth0":{"Tx":"100","Rx":"100"}, "eth1":{"Tx":"0","Rx":"0"}, "lo":{"Tx":"0","Rx":"0"} }
我不确定如何遍历JSON数据-它可能适用于任意数量的接口。
有人可以帮我吗?提前致谢
您可以遍历父对象和子对象的属性:
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]; } } } }