javascript tutorial - [Solved-5 Solutions] List the properties of javascript object - javascript - java script - javascript array
Problem:
Say we create an object thus:
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:
Solution 1:
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) we can use the built in Object.keys method:
The above has a full polyfill but a simplified version is:
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.
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:
Solution 4:
Could do it with jQuery as follows:
Solution 5:
if we are trying to get the elements only but not the functions then this code can help you
This is part of my implementation of the HashMap and WE only want the keys, "this" is the hashmap object that contains the keys