Home > Web Front-end > JS Tutorial > How Can I Efficiently Get a List of JavaScript Object Property Names?

How Can I Efficiently Get a List of JavaScript Object Property Names?

Linda Hamilton
Release: 2024-12-05 12:09:14
Original
414 people have browsed it

How Can I Efficiently Get a List of JavaScript Object Property Names?

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://.*"};
Copy after login

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);
Copy after login

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;
};
Copy after login

An alternative approach involves extending the Object prototype:

Object.prototype.keys = function() {
   var keys = [];
   for (var key in this) {
      keys.push(key);
   }
   return keys;
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template