Queryer
Queryer

Reputation: 259

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?

Upvotes: 12

Views: 49614

Answers (11)

gondwe
gondwe

Reputation: 101

stop reinventing the wheel !

Object.keys()

MDN

Upvotes: 0

Tukaram Patil Pune
Tukaram Patil Pune

Reputation: 809

var _ = require('underscore');

var obj = [{"A":20,"B":32,"C":27,"D":30,"E":40},{"F":50}, {"G":60,"H":70},{"I":80}];

var keys = [], values = [];



_.each(obj, function(d) {

     keys.push(_.keys(d));

     values.push(_.values(d));
});


// Keys   ->  [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' ]
console.log('Keys   -> ', _.flatten(keys ));
// Values ->  [ 20, 32, 27, 30, 40, 50, 60, 70, 80 ]
console.log('Values -> ', _.flatten(values));

Upvotes: 0

user1686644
user1686644

Reputation: 21

I think this should be parsed recursively like below

var getKeys = function(previousKeys,obj){
        var currentKeys = Object.keys(obj);
        previousKeys = previousKeys.concat(currentKeys);
        for(var i=0;i<currentKeys.length;i++){
            var innerObj = obj[currentKeys[i]];
            if(innerObj!==null && typeof innerObj === 'object' && !Array.isArray(innerObj)){
            return this.getKeys(previousKeys,innerObj);
            }
        }
        return previousKeys;
    }

usage: getKeys([],{"a":"1",n:{c:"3",e:{ f:4,g:[1,2,3]}}})

Result: ["a", "n", "c", "e", "f", "g"]

Upvotes: 0

sangeeth kumar
sangeeth kumar

Reputation: 327

Try this. It is simple:

var a = [{"A":20,"B":32,"C":27,"D":30,"E":40}];

for(var i in a){
  for(var j in a[i]){
    console.log(j); // shows key
    console.log(a[i][j]); // shows value
  }
}

Upvotes: 0

Billy Moon
Billy Moon

Reputation: 58561

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")

defensively

Including @Sahil's defensive method...

for (var key in easy) {
    if (easy.hasOwnProperty(key)) {
        keys.push(key)
        vals.push(easy[key])
    }
}

Upvotes: 4

Do-Gyun Kim
Do-Gyun Kim

Reputation: 21

I think this is the simplest.

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

Result :

["A", "B", "C", "D", "E"]

Upvotes: 2

nrabinowitz
nrabinowitz

Reputation: 55678

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

Upvotes: 18

Jord&#227;o
Jord&#227;o

Reputation: 56487

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;

Upvotes: 4

Sahil Muthoo
Sahil Muthoo

Reputation: 12496

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;
    };

Upvotes: 11

maerics
maerics

Reputation: 156494

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"]

Upvotes: 2

sjngm
sjngm

Reputation: 12861

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);

Upvotes: 0

Related Questions