How to list the properties of a JavaScript object?

Viewed 891658

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"]
18 Answers

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.

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 */
    }
}

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()]

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

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.

Related