Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  78] [ 6]  / answers: 1 / hits: 49606  / 13 Years ago, mon, september 12, 2011, 12:00:00

I have a question that would like to seek your expertise on.



This is a JSON array that I have:



[{A:20,B:32,C:27,D:30,E:40}]


What I would like to do is to retrieve the keys (A, B, C, D, E) from the JSON array instead of the values. I am able to retrieve the values but not the keys.



I am using this to retrieve the values dynamically:



function calculateSum(jsonArray) {
var result = 0;
for (var i = jsonArray.length - 1; i >= 0; --i)
{
var o = jsonArray[i];
A = o.A;
B = o.B;
C = o.C;
D = o.D;
E = o.E;
result = A + B + C + D + E;
return result;
}

return result;
}


Similarly, what should I do to retrieve the keys using JavaScript?


More From » json

 Answers
68

Are you using D3.js as your tag implies? Because in that case, you can just use d3.keys():



var data = [{A:20,B:32,C:27,D:30,E:40}];
d3.keys(data[0]); // [A, B, C, D, E]


If you want the sum of all the values, you might be better off using d3.values() and d3.sum():



var data = [{A:20,B:32,C:27,D:30,E:40}, {F:50}];
// get total of all object totals
var total = d3.sum(data, function(d) {
// get total of a single object's values
return d3.sum(d3.values(d));
});
total; // 199

[#90140] Saturday, September 10, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
lucianod questions
;