snippetjavascriptCritical
How to list the properties of a JavaScript object?
Viewed 0 times
objecthowpropertiesthelistjavascript
Problem
Say I create an object thus:
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:
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"]Solution
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:
The above has a full polyfill but a simplified version is:
Alternatively replace
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.Code Snippets
var keys = Object.keys(myObject);var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}Context
Stack Overflow Q#208016, score: 1237
Revisions (0)
No revisions yet.