Max
Max

Reputation: 33

Ways to get to know of key names inside a javascript object literal

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

Answers (4)

Lix
Lix

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

thefourtheye
thefourtheye

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

Richard Dalton
Richard Dalton

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

benhowdle89
benhowdle89

Reputation: 37474

Object.keys()

var keys = Object.keys(objA);

Upvotes: 0

Related Questions