Reputation: 33
declare a javascript object literal
var objA = {'keyA':'valA'}
in the console
objA
> Object {keyA: "valA"}
the object is not an array
objA[0]
> undefined
the only way I know to get key names is to cicle on the object
for (x in objA) {
console.log(x);
}
> keyA
Do you know any other ways to get key names from object?
Upvotes: 1
Views: 122
Reputation: 47976
You could use Object.keys()
do this:
var objA = { 'keyA': 'valA', 'foo': 'bar' };
Object.keys( objA ); // [ 'keyA', 'foo' ]
Note that this is not supported on all browsers yet - but it is on the modern versions of the popular ones.
Upvotes: 0
Reputation: 239503
You can use Object.keys
like this
var objA = {'keyA':'valA'};
console.log(Object.keys(objA));
Object.keys will not work on older versions of JavaScript, so you can use a for..in
loop like this
var objA = {'keyA':'valA'}, keys = [];
for (var key in objA) {
keys.push(key);
}
Upvotes: 1
Reputation: 35793
Object.keys function is available in newer browsers:
var keys = Object.keys(objA);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Upvotes: 0