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

This is my 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?

share|improve this question

6 Answers

up vote 4 down vote accepted

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
share|improve this answer

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;
    };
share|improve this answer
+1 This is not really a problem for a JSON-deserialized object, but you're right, the code is better with the check. I'll add it to my answer... – Jordão Sep 12 '11 at 17:29

Try using the JavaScript for..in statement:

var getKeys = function(arr) {
  var key, keys = [];
  for (i=0; i<arr.length; i++) {
    for (key in arr[i]) {
      keys.push(key);
    }
  }
  return keys;
};

var a = [{"A":20, "B":32, "C":27, "D":30, "E":40}, {"F":50}]
getKeys(a); // => ["A", "B", "C", "D", "E", "F"]
share|improve this answer

Use for .. in:

var result = 0;

for (var i = jsonArray.length - 1; i >= 0; --i) {
    var o = jsonArray[i];
    for (var key in o) {
      if (o.hasOwnProperty(key)) {
        result += o[key];
      }
    }
    // in your code, you return result here, 
    // which might not give the right result 
    // if the array has more than 1 element
}

return result;
share|improve this answer
This just sums up the values. I believe @Queryer wants to retrieve the list of keys. – Sahil Muthoo Sep 12 '11 at 17:29
@Sahil Muthoo: That's not what I understood.... To me he wants to sum up the values, but without knowing the keys beforehand.... – Jordão Sep 12 '11 at 17:33
var easy = {
    a: 1,
    b: 2,
    c: 3
}

var keys = [], vals = []
for (var key in easy) {
    keys.push(key)
    vals.push(easy[key])
}

alert(keys+" - tha's how easy baby, it's gonna be")
alert(vals+" - tha's how easy baby, it's gonna be")
share|improve this answer

A for-in-loop does the trick. On one object it looks like this:

var o = {
    a: 5,
    b: 3
};
var num = 0;

for (var key in o) {
    num += o[key];
}
alert(num);
share|improve this answer
This just sums up the values. I believe @Queryer wants to retrieve the list of keys. – Sahil Muthoo Sep 12 '11 at 17:31

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.