Getting JavaScript object key list

Getting JavaScript object key list

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?

Solutions/Answers:

Solution 1:

var keys = [];
for(var k in obj) keys.push(k);

alert("total " + keys.length + " keys: " + keys);

Solution 2:

var obj = {
   key1: 'value1',
   key2: 'value2',
   key3: 'value3',
   key4: 'value4'
}
var keys = Object.keys(obj);
console.log('obj contains ' + keys.length + ' keys: '+  keys);

It’s supported on most major browsers now.

Solution 3:

Underscore.js makes the transformation pretty clean:

var keys = _.map(x, function(v, k) { return k; });

Edit: I missed that you can do this too:

var keys = _.keys(x);

Solution 4:

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

Solution 5:

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];

Solution 6:

obj = {'a':'c','b':'d'}

You can try:

[index for (index in obj)] 

this will return:

['a','b']

to get the list of keys
or

[obj[index] for (index in obj)]

to get the values