从 JSON 数组键值对动态检索键 - Javascript [英] Retrieving Keys from JSON Array key-value pair dynamically - Javascript
问题描述
我有一个问题想请教您的专业知识.
I have a question that would like to seek your expertise on.
这是我拥有的 JSON 数组:
This is a JSON array that I have:
[{"A":20,"B":32,"C":27,"D":30,"E":40}]
我想做的是从 JSON 数组中检索键(A、B、C、D、E)而不是值.我能够检索值但不能检索键.
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;
}
同样,我应该怎么做才能使用 JavaScript 检索键?
Similarly, what should I do to retrieve the keys using JavaScript?
推荐答案
你在使用 D3.js正如您的标签所暗示的那样?因为在那种情况下,你可以只使用 d3.keys()
:
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"]
如果您想要所有值的总和,最好使用 d3.values()
和 d3.sum()
:
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
这篇关于从 JSON 数组键值对动态检索键 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!