-3

Say I have an object which is as follows:

var myObj = {FOO: 0, BAR: 1};

How can I get the string value of one of the keys?

If I do a:

console.log(myObj.FOO);

It will print 0 whereas I want to print 'FOO'.

How can this be achieved?

4
  • 2
    Object.keys Commented Aug 5, 2015 at 19:45
  • 1
    You already know the key is "FOO", why not just log "FOO"? Commented Aug 5, 2015 at 19:46
  • The key you use to access a property on an object is literally a string value already. Commented Aug 5, 2015 at 19:46
  • You want the key, not the value. Commented Aug 5, 2015 at 19:47

3 Answers 3

1

You can use the Object.keys() method. The following returns "FOO":

Object.keys(myObj)[0];

For more on Object.keys():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Sign up to request clarification or add additional context in comments.

1 Comment

Although you would probably never be bitten by this, the order of those keys is implementation dependent and aren't even guaranteed to return in the same order (although they probably will be).
1

to display the property names, you can loop through them:

for (name in obj) {
  alert("This is the key: " + name);
  alert("This is the value: " + obj[name]);
}

Comments

0

You can log object property names through a loop.

var myObj = { FOO : 0, BAR : 1 };

for( var propertyName in myObj ) {

    console.log( propertyName );

}

Or you can retrieve object property names on a 0 indexed array using Object.getOwnPropertyNames.

var myObj = { FOO : 0, BAR : 1 };

var propertyNames = Object.getOwnPropertyNames( myObj );

console.log( propertyNames[ 0 ] ); //This shold log "FOO"

Or you can achieve the same result as above using Object.keys.

var myObj = { FOO : 0, BAR : 1 };

var propertyNames = Object.keys( myObj );

console.log( propertyNames[ 0 ] ); //This shold log "FOO"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.