javascript tutorial - [Solved-5 Solutions] List the properties of javascript object - javascript - java script - javascript array



Problem:

Say we create an object thus:

var myObject =
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
click below button to copy the code. By JavaScript tutorial team

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

keys == ["ircEvent", "method", "regex"]
click below button to copy the code. By JavaScript tutorial team

Solution 1:

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

var keys = Object.keys(myObject);
click below button to copy the code. By JavaScript tutorial team

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;
}
click below button to copy the code. By JavaScript tutorial team

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

Solution 2:

As slashnick pointed out, we 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 we want to iterate only over the object's own attributes, we can make use of the Object#hasOwnProperty() method. Thus having the following.

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

click below button to copy the code. By JavaScript tutorial team

Solution 3:

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

var o = {"foo": 1, "bar": 2}; 
alert(Object.keys(o));
click below button to copy the code. By JavaScript tutorial team

Solution 4:

Could do it with jQuery as follows:

var objectKeys = $.map(object, function(value, key) {
  return key;
});
click below button to copy the code. By JavaScript tutorial team

Solution 5:

if we 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;
}
click below button to copy the code. By JavaScript tutorial team

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


Related Searches to javascript tutorial - List the properties of javascript object