Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  187] [ 6]  / answers: 1 / hits: 26000  / 15 Years ago, wed, july 29, 2009, 12:00:00

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


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


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


More From » jquery

 Answers
29

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

[#99036] Thursday, July 23, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rafael

Total Points: 5
Total Questions: 103
Total Answers: 103

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;