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

balteo
  • 23,602
  • 63
  • 219
  • 412

3 Answers3

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]);
}
bloC
  • 526
  • 3
  • 16
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

Maverick976
  • 528
  • 1
  • 4
  • 11
  • 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). – Matt Burland Aug 05 '15 at 19:54
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"
Mario
  • 91
  • 1
  • 6