tags:

views:

84

answers:

4

I have a Javascript Object like

var obj = {
   key1: 'value1',
   key2: 'value2',
   key3: 'value3',
   key4: 'value4'
}

How can I get the length and list of keys in this object?

+5  A: 
var keys = [];
for(var k in obj) keys.push(k);

alert("total " + keys.length + " keys: " + keys);
zed_0xff
+1 Beautifully concise
Jamie Wong
I don't suppose Javascript is like PHP, where you can skip the first line altogether? Not that something like that is advisable to do anyway.
Bart van Heukelom
@Bart: No, the first line is necessary in JavaScript.
Daniel Vassallo
You should take a look at David Morrissey's comment below for an edge case here. Sometimes taking this approach will result in unwanted members of the prototype showing up in `keys`.
pat
@pat: If you're using object literals, that'll only happen if you extend `Object.prototype`, which you should not be doing anyway. For custom constructors, though, you are right.
musicfreak
A: 
var keys = new Array();
for(var key in obj)
{
   keys[keys.length] = key;
}

var keyLength = keys.length;

to access any value from the object, you can use obj[key];

mohang
+2  A: 
Object.keys(obj); // ['key1', 'key2', 'key3', 'key4']

It's an addition in ECMAScript 5, and only works on Chrome currently.

Anurag
+3  A: 

If you only want the keys which are specific to that particular object and not any derived prototype properties:

function getKeys(obj) {
    var r = []
    for (var k in obj) {
        if (!obj.hasOwnProperty(k)) 
            continue
        r.push(k)
    }
    return r
}

e.g:

var keys = getKeys({'eggs': null, 'spam': true})
var length = keys.length // access the `length` property as usual for arrays
David Morrissey