Getting JavaScript object key list

  1. Home
  2. javascript
  3. 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?

First answer

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

for (var k in obj) keys.push(k);

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

Second answer

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

Third answer

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
Reprint:https://stackoverflow.com/questions/3068534/getting-javascript-object-key-list
Spread the love

Related articles

Comments are closed.