Listing Properties of JavaScript Objects
When working with JavaScript objects, retrieving a list of property names can be essential. Suppose you have an object defined as follows:
var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
The question arises: how can we efficiently obtain a list of the property names (e.g., ["ircEvent", "method", "regex"])?
Modern Browsers:
In modern browsers, the built-in Object.keys method provides an elegant solution:
var keys = Object.keys(myObject);
Polyfill for Legacy Browsers:
For browsers lacking native support, a simplified polyfill can be implemented:
var getKeys = function(obj) { var keys = []; for (var key in obj) { keys.push(key); } return keys; };
An alternative approach involves extending the Object prototype:
Object.prototype.keys = function() { var keys = []; for (var key in this) { keys.push(key); } return keys; };
This method allows you to call .keys() on any object. However, extending the prototype may have side effects and is generally not recommended.
The above is the detailed content of How Can I Efficiently Get a List of JavaScript Object Property Names?. For more information, please follow other related articles on the PHP Chinese website!