Home >Web Front-end >JS Tutorial >How Can I Get a List of JavaScript Object Properties?
Listing Properties of a JavaScript Object
In JavaScript, there are several approaches to obtain a list of properties associated with an object.
Using Object.keys Method:
The Object.keys() method is available in modern browsers and provides a concise and efficient way to retrieve property names. For instance:
var myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; var keys = Object.keys(myObject);
Polyfill for Object.keys:
If you need to support older browsers, you can use a polyfill for Object.keys:
var getKeys = function(obj) { var keys = []; for (var key in obj) { keys.push(key); } return keys; };
Custom Prototype Method:
You can also extend the Object prototype to add the keys() method:
Object.prototype.keys = function() { var keys = []; for (var key in this) { keys.push(key); } return keys; };
This allows you to call .keys() on any object:
myObject.keys(); // Returns ["ircEvent", "method", "regex"]
Each of these methods returns an array containing the property names of the object.
The above is the detailed content of How Can I Get a List of JavaScript Object Properties?. For more information, please follow other related articles on the PHP Chinese website!