使用JavaScript访问数组中的键

时间:2011-06-10 14:55:35

标签: javascript

RaceArray: [{
    Unknown: 0,
    Caucasian: 1,
    AfricanAmerican: 2,
    AmericanIndian: 3,
    Asian: 4,
    Hispanic: 5,
    Other: 6
 }]

如何在JavaScript中单独访问密钥并将其作为单独的数组形成。

期望的结果......

RaceArray = ['Unknown','Caucasian']

3 个答案:

答案 0 :(得分:5)

var RaceObj = [{
    Unknown: 0,
    Caucasian: 1,
    AfricanAmerican: 2,
    AmericanIndian: 3,
    Asian: 4,
    Hispanic: 5,
    Other: 6
}];

var obj = RaceObj[0], Keys = [];
for(var key in obj){
  if(obj.hasOwnProperty(key)){
    Keys.push(key);
  }
}

答案 1 :(得分:0)

我认为这与此问题类似:JavaScript: Getting the object's property name

答案 2 :(得分:-1)

可能有一个更简单的解决方案,但你可以这样做:

var keys = [];
for(var key in RaceObj) {
    if (RaceObj.hasOwnProperty(key)) {
        keys.push(key);
    }
}