从JSON数组键值对动态检索键 - Javascript [英] Retrieving Keys from JSON Array key-value pair dynamically - Javascript

查看:114
本文介绍了从JSON数组键值对动态检索键 - 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}]

我想要做的是检索键(A,B,C,D,E) JSON数组,而不是值。

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屋!

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