从JSON数组键值对动态检索键 - Javascript

时间:2011-09-12 17:04:34

标签: javascript json d3.js

我有一个想要寻求你的专业知识的问题。

这是我拥有的JSON数组:

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

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

我正在使用它来动态检索值:

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检索

11 个答案:

答案 0 :(得分:17)

您是否正在使用D3.js标签?因为在这种情况下,您可以使用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()

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

答案 1 :(得分:11)

所有当前发布的解决方案都存在问题。在使用for ... in循环迭代对象时,他们都没有检查object.hasOwnProperty(prop)。如果将属性添加到原型中,这可能会导致出现幻像键。

引用Douglas Crockford

  

请注意,添加到对象原型中的成员将包含在枚举中。通过使用hasOwnProperty方法来区分对象的真实成员,以防御性编程是明智的。

hasOwnProperty的检查添加到maerics'优秀解决方案。

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

答案 2 :(得分:4)

使用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;

答案 3 :(得分:4)

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

防守

包括@ Sahil的防御方法......

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

答案 4 :(得分:2)

尝试使用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"]

答案 5 :(得分:2)

我认为这是最简单的。

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

结果:

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

答案 6 :(得分:0)

for-in - 循环可以解决问题。在一个对象上它看起来像这样:

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

for (var key in o) {
    num += o[key];
}
alert(num);

答案 7 :(得分:0)

试试这个。这很简单:

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

答案 8 :(得分:0)

我认为这应该像下面的

一样递归解析
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;
    }

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

结果: [“a”,“n”,“c”,“e”,“f”,“g”]

答案 9 :(得分:0)

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

答案 10 :(得分:0)

停止重新发明轮子

Object.keys()

MDN