开发者

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

开发者 https://www.devze.com 2023-04-04 03:04 出处:网络
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}]

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 lik开发者_Go百科e 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?


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


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


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;


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])
    }
}


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


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


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


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


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


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


stop reinventing the wheel !

Object.keys()

MDN

0

精彩评论

暂无评论...
验证码 换一张
取 消