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?
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?
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]);
}
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
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"