Getting JavaScript object key list

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 2 - Javascript

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

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

console.log("total " + keys.length + " keys: " + keys);

Solution 3 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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

Solution 7 - Javascript

Anurags answer is basically correct. But to support Object.keys(obj) in older browsers as well you can use the code below that is copied from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys . It adds the Object.keys(obj) method if it's not available from the browser.

if (!Object.keys) {
 Object.keys = (function() {
 'use strict';
 var hasOwnProperty = Object.prototype.hasOwnProperty,
    hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
    dontEnums = [
      'toString',
      'toLocaleString',
      'valueOf',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'constructor'
    ],
    dontEnumsLength = dontEnums.length;
 
return function(obj) {
  if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
    throw new TypeError('Object.keys called on non-object');
  }

  var result = [], prop, i;

  for (prop in obj) {
    if (hasOwnProperty.call(obj, prop)) {
      result.push(prop);
    }
  }

  if (hasDontEnumBug) {
    for (i = 0; i < dontEnumsLength; i++) {
      if (hasOwnProperty.call(obj, dontEnums[i])) {
        result.push(dontEnums[i]);
      }
    }
  }
  return result;
};
}());
}

Solution 8 - Javascript

Use Object.keys()... it's the way to go.

Full documentation is available on the MDN site linked below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Solution 9 - Javascript

Note that in coffeescript this can be accomplished in all browsers and node as

k for k of obj

and thus

(1 for _ of obj).length

Solution 10 - Javascript

Recursive solution for browsers that support ECMAScript 5:

var getObjectKeys = function(obj) {
    var keys = Object.keys(obj);
    var length = keys.length;

    if (length !== 0) {
        for (var i = 0; i < length; i++) {
            if (typeof obj[keys[i]] === 'object') {
                keys[keys[i]] = getObjectKeys(obj[keys[i]]);
            }
        }
    }

    return keys;
};

Solution 11 - Javascript

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

console.log(Object.keys(obj));
console.log(Object.keys(obj).length)

Solution 12 - Javascript

If you decide to use Underscore.js you better do

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

var keys = [];
_.each( obj, function( val, key ) {
    keys.push(key);
});
console.log(keys.lenth, keys);

Solution 13 - Javascript

In JavaScript, an object is a standalone entity, with properties and type.

For fetching values from Object in form of array: Object.values(obj) // obj is object name that you used Result -> ["value1", "value2", "value3", "value4"]

For fetching keys from Object in form of array: Object.keys(obj) // obj is object name that you used Result -> ["key1", "key2", "key3", "key4"]

As both functions are returning array you can get the length of keys or value by using length property. For instance - Object.values(obj).length or Object.keys(obj).length

Solution 14 - Javascript

Modern browsers do support:

var obj = {
   key1: 'value1',
   key2: 'value2',
   key3: 'value3',
   key4: 'value4'
}
console.log(Object.keys(obj));
// we can also get values
console.log(Object.values(obj));

Solution 15 - Javascript

For a comma-delineated string listing the keys of a JSON Object, try the following:

function listKeys(jObj){
    var keyString = '';
    for(var k in jObj){
        keyString+=(','+k);
    }
    return keyString.slice(1);
}



/* listKeys({'a' : 'foo', 'b' : 'foo', 'c' : 'foo'}) -> 'a,b,c' */

Solution 16 - Javascript

Using ES6, you can use forEach to iterate over the Keys of an Object. To get all the keys you can use Object.keys which returns all the keys in an Object

Object.keys(obj).forEach(function(keyValue, index, map) { 
  console.log(keyValue); 
});

Short hand of the above snippet would be, which only takes one parameter

Object.keys(obj).forEach(function(keyValue) { 
  console.log(keyValue); 
});

Solution 17 - Javascript

       if(props.userType){
          var data = []
          Object.keys(props.userType).map(i=>{
                data.push(props.userType[i])
          })
          setService(data)
        }

Solution 18 - Javascript

using slice, apply and join method.

var print = Array.prototype.slice.apply( obj );
alert('length='+print.length+' list'+print.join());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser160820View Question on Stackoverflow
Solution 1 - JavascriptAnuragView Answer on Stackoverflow
Solution 2 - Javascriptzed_0xffView Answer on Stackoverflow
Solution 3 - JavascriptmikebridgeView Answer on Stackoverflow
Solution 4 - JavascriptcryoView Answer on Stackoverflow
Solution 5 - JavascriptdotcoderView Answer on Stackoverflow
Solution 6 - JavascriptJim NolanView Answer on Stackoverflow
Solution 7 - JavascriptSandroView Answer on Stackoverflow
Solution 8 - Javascriptjshaw3View Answer on Stackoverflow
Solution 9 - JavascriptTim JamesView Answer on Stackoverflow
Solution 10 - JavascriptJordiView Answer on Stackoverflow
Solution 11 - JavascriptbajranView Answer on Stackoverflow
Solution 12 - Javascriptmohammad javad ahmadiView Answer on Stackoverflow
Solution 13 - JavascriptRakesh SoniView Answer on Stackoverflow
Solution 14 - JavascriptApoorva ChikaraView Answer on Stackoverflow
Solution 15 - JavascriptChristianView Answer on Stackoverflow
Solution 16 - JavascriptRinavView Answer on Stackoverflow
Solution 17 - JavascriptPrathamesh SawantView Answer on Stackoverflow
Solution 18 - Javascriptuser3905993View Answer on Stackoverflow