How to list the properties of a JavaScript object?

Javascript

Javascript Problem Overview


Say I create an object thus:

var myObject =
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:

keys == ["ircEvent", "method", "regex"]

Javascript Solutions


Solution 1 - Javascript

In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var keys = Object.keys(myObject);

The above has a full polyfill but a simplified version is:

var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}

Alternatively replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.

Solution 2 - Javascript

As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        /* useful code here */
    }
}

Solution 3 - Javascript

As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. Object.keys() will do what you want and is supported in Firefox 4, Chrome 6, Safari 5 and IE 9.

You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. Here's a more compatible solution:

Object.keys = Object.keys || (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
        DontEnums = [ 
            'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
            'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
        ],
        DontEnumsLength = DontEnums.length;
        
    return function (o) {
        if (typeof o != "object" && typeof o != "function" || o === null)
            throw new TypeError("Object.keys called on a non-object");
    
        var result = [];
        for (var name in o) {
            if (hasOwnProperty.call(o, name))
                result.push(name);
        }
    
        if (hasDontEnumBug) {
            for (var i = 0; i < DontEnumsLength; i++) {
                if (hasOwnProperty.call(o, DontEnums[i]))
                    result.push(DontEnums[i]);
            }   
        }
    
        return result;
    };
})();

Note that the currently accepted answer doesn't include a check for hasOwnProperty() and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.

Implementing Object.keys() will give you a more robust solution.

EDIT: following a recent discussion with kangax, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his Object.forIn() function found here.

Solution 4 - Javascript

Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.

For example:

var o = {"foo": 1, "bar": 2}; 
alert(Object.keys(o));

ECMAScript 5 compatibility table: http://kangax.github.com/es5-compat-table/

Description of new methods: http://markcaudill.com/index.php/2009/04/javascript-new-features-ecma5/

Solution 5 - Javascript

Object.getOwnPropertyNames(obj)

This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

In JS, every property has a few properties, including a boolean enumerable.

In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

Example:

var o = Object.create({base:0})
Object.defineProperty(o, 'yes', {enumerable: true})
Object.defineProperty(o, 'not', {enumerable: false})

console.log(Object.getOwnPropertyNames(o))
// [ 'yes', 'not' ]

console.log(Object.keys(o))
// [ 'yes' ]

for (var x in o)
    console.log(x)
// yes, base

Also note how:

  • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
  • for in does

More about the prototype chain here: https://stackoverflow.com/a/23877420/895245

Solution 6 - Javascript

Solution 7 - Javascript

Could do it with jQuery as follows:

var objectKeys = $.map(object, function(value, key) {
  return key;
});

Solution 8 - Javascript

if you are trying to get the elements only but not the functions then this code can help you

this.getKeys = function() {

    var keys = new Array();
    for(var key in this) {

        if( typeof this[key] !== 'function') {

            keys.push(key);
        }
    }
    return keys;
}

this is part of my implementation of the HashMap and I only want the keys, "this" is the hashmap object that contains the keys

Solution 9 - Javascript

This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.

var myJSONObject =  {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);

Solution 10 - Javascript

Under browsers supporting js 1.8:

[i for(i in obj)]

Solution 11 - Javascript

Mozilla has full implementation details on how to do it in a browser where it isn't supported, if that helps:

if (!Object.keys) {
  Object.keys = (function () {
    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 = [];

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

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

You could include it however you'd like, but possibly in some kind of extensions.js file at the top of your script stack.

Solution 12 - Javascript

Use Reflect.ownKeys()

var obj = {a: 1, b: 2, c: 3};
Reflect.ownKeys(obj) // ["a", "b", "c"]

Object.keys and Object.getOwnPropertyNames cannot get non-enumerable properties. It's working even for non-enumerable properties.

var obj = {a: 1, b: 2, c: 3};
obj[Symbol()] = 4;
Reflect.ownKeys(obj) // ["a", "b", "c", Symbol()]

Solution 13 - Javascript

With ES6 and later (ECMAScript 2015), you can get all properties like this:

let keys = Object.keys(myObject);

And if you wanna list out all values:

let values = Object.keys(myObject).map(key => myObject[key]);

Solution 14 - Javascript

Building on the accepted answer.

If the Object has properties you want to call say .properties() try!

var keys = Object.keys(myJSONObject);

for (var j=0; j < keys.length; j++) {
  Object[keys[j]].properties();
}

Solution 15 - Javascript

Since I use underscore.js in almost every project, I would use the keys function:

var obj = {name: 'gach', hello: 'world'};
console.log(_.keys(obj));

The output of that will be:

['name', 'hello']

Solution 16 - Javascript

IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.

It seems stackoverflow does some stupid filtering.

The list is available at the bottom of this google group post:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0

Solution 17 - Javascript

A lot of answers here... This is my 2 cents.

I needed something to print out all the JSON attributes, even the ones with sub-objects or arrays (parent name included).

So - For this JSON:

mylittleJson = {
  "one": "blah",
  "two": {
	  "twoone": "",
	  "twotwo": "",
	  "twothree": ['blah', 'blah']
  },
  "three": ""
}

It'd print this:

.one
.two.twoone
.two.twotwo
.two.twothree
.three

Here is function

function listatts(parent, currentJson){
   var attList = []
   if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length > 0) {
      return
   }
   for(var attributename in currentJson){
       if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) {
           childAtts = listatts(parent + "." + attributename, currentJson[attributename])
           if (childAtts != undefined && childAtts.length > 0)
               attList = [...attList, ...childAtts]
           else 
               attList.push(parent + "." + attributename)
       }
   }
   return attList
}

Hope it helps too.

Solution 18 - Javascript

The solution work on my cases and cross-browser:

var getKeys = function(obj) {
    var type = typeof  obj;
    var isObjectType = type === 'function' || type === 'object' || !!obj;

    // 1
    if(isObjectType) {
        return Object.keys(obj);
    }

    // 2
    var keys = [];
    for(var i in obj) {
        if(obj.hasOwnProperty(i)) {
            keys.push(i)
        }
    }
    if(keys.length) {
        return keys;
    }

    // 3 - bug for ie9 <
    var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
    if(hasEnumbug) {
        var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
            'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

        var nonEnumIdx = nonEnumerableProps.length;

        while (nonEnumIdx--) {
            var prop = nonEnumerableProps[nonEnumIdx];
            if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                keys.push(prop);
            }
        }

    }

    return keys;
};

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
QuestionjohnstokView Question on Stackoverflow
Solution 1 - JavascriptslashnickView Answer on Stackoverflow
Solution 2 - JavascriptPablo CabreraView Answer on Stackoverflow
Solution 3 - JavascriptAndy EView Answer on Stackoverflow
Solution 4 - JavascriptSam DuttonView Answer on Stackoverflow
Solution 5 - JavascriptCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 6 - JavascriptMattView Answer on Stackoverflow
Solution 7 - JavascriptsbonamiView Answer on Stackoverflow
Solution 8 - JavascriptzeacussView Answer on Stackoverflow
Solution 9 - Javascriptqwerty_jonesView Answer on Stackoverflow
Solution 10 - JavascriptRix BeckView Answer on Stackoverflow
Solution 11 - JavascriptKristofer SommestadView Answer on Stackoverflow
Solution 12 - JavascriptsametView Answer on Stackoverflow
Solution 13 - JavascriptAnh HoangView Answer on Stackoverflow
Solution 14 - JavascriptSydwellView Answer on Stackoverflow
Solution 15 - JavascriptschmijosView Answer on Stackoverflow
Solution 16 - JavascriptGareth HeyesView Answer on Stackoverflow
Solution 17 - JavascriptfebaisiView Answer on Stackoverflow
Solution 18 - Javascriptchristian NguyenView Answer on Stackoverflow