How to list the properties of a JavaScript object

var myJSONObject =
        {"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"]

  

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

var keys = Object.keys(myJSONObject);

  

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

  

posted @ 2015-06-20 00:38  hephec  阅读(175)  评论(0编辑  收藏  举报