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

How can i access the key's alone in my JavaScript and form it as an separate array.

Desired outcome...

RaceArray = ['Unknown','Caucasian']
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
John Cooper
  • 7,343
  • 31
  • 80
  • 100
  • 1
    I'm not 100% sure what you're asking. You've posted the before, maybe post the after (desired outcome)? – Brad Christie Jun 10 '11 at 14:57
  • 1
    may be you want array like ["unknown","caucasian".....] ? – Rizwan Sharif Jun 10 '11 at 14:57
  • Apart from the (not very good) coding question my advise would be to study the concept of *race* first. Start @ http://en.wikipedia.org/wiki/Race_(classification_of_humans) – KooiInc Jun 10 '11 at 15:50

2 Answers2

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);
  }
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
-1

There may be a simpler solution but you can do:

var keys = [];
for(var key in RaceObj) {
    if (RaceObj.hasOwnProperty(key)) {
        keys.push(key);
    }
}
John Kalberer
  • 5,690
  • 1
  • 23
  • 27
  • Note that `RaceObj` is an array **first** and an object **second**. You'll need to iterate the array before retrieving the keys. – Brad Christie Jun 10 '11 at 14:59
  • 1
    aham i will recommend not to use for (var key in obj) .. instead use jquery's $.each or put if condition checking if the property belongs to object and not its prototype – Rizwan Sharif Jun 10 '11 at 14:59
  • You should use `hasOwnProperty` to only get own properties. – Gumbo Jun 10 '11 at 15:00
  • @RizwanSharif: Why involve a jQuery object in this? Are you aware `.each()` [uses for(... in ...) already](https://github.com/jquery/jquery/blob/master/src/core.js#L604-642)? – Brad Christie Jun 10 '11 at 15:01
  • When iterating over objects like this, you *always* need to use a `hasOwnProperty` check, otherwise properties that exist on the prototype will be iterated over as well, which is usually not expected behavior. – Austin Hyde Jun 10 '11 at 15:03