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']
3
  • 1
    I'm not 100% sure what you're asking. You've posted the before, maybe post the after (desired outcome)? Commented Jun 10, 2011 at 14:57
  • 1
    may be you want array like ["unknown","caucasian".....] ? Commented Jun 10, 2011 at 14:57
  • Apart from the (not very good) coding question my advise would be to study the concept of race first. Start @ en.wikipedia.org/wiki/Race_(classification_of_humans) Commented Jun 10, 2011 at 15:50

2 Answers 2

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

what is RaceObj[0] here... why do we use it.
@John: In your RaceArray, you have an array containing 1 element, an object. So, RaceObj[0] gets that object. I also renamed RaceArray to RaceObj.
-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);
    }
}

5 Comments

Note that RaceObj is an array first and an object second. You'll need to iterate the array before retrieving the keys.
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
You should use hasOwnProperty to only get own properties.
@RizwanSharif: Why involve a jQuery object in this? Are you aware .each() uses for(... in ...) already?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.