Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving Keys from JSON Array key-value pair dynamically - Javascript

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?

like image 239
Queryer Avatar asked Sep 12 '11 17:09

Queryer


People also ask

How do I iterate keys in JSON?

Use Object. keys() to get keys array and use forEach() to iterate over them.

How can I get the key-value in a JSON object?

To get a JSON object's key and value in JavaScript, we can use the JSON. parse method to parse the JSON object string into a JavaScript object. Then we can get a property's value as we do with any other JavaScript object.

How do you add a key-value pair in an object dynamically?

To add dynamic key-value pairs to a JavaScript array or hash table, we can use computed key names. const obj = {}; obj[name] = val; to add a property with the value of name string as the property name. We assign val to as the property's value.


2 Answers

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
like image 190
nrabinowitz Avatar answered Oct 04 '22 19:10

nrabinowitz


All of the current posted solutions have a problem. None of them check for object.hasOwnProperty(prop) while iterating over an object using a for...in loop. This might cause phantom keys to appear if properties are added to the prototype.

Quoting Douglas Crockford

Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object.

Adding a check for hasOwnProperty to maerics' excellent solution.

var getKeys = function (arr) {
        var key, keys = [];
        for (i = 0; i < arr.length; i++) {
            for (key in arr[i]) {
                if (arr[i].hasOwnProperty(key)) {
                    keys.push(key);
                }
            }
        }
        return keys;
    };
like image 33
Sahil Muthoo Avatar answered Oct 04 '22 18:10

Sahil Muthoo