Home > Web Front-end > JS Tutorial > How Do I Enumerate and Filter JavaScript Object Properties?

How Do I Enumerate and Filter JavaScript Object Properties?

DDD
Release: 2024-12-16 13:24:12
Original
718 people have browsed it

How Do I Enumerate and Filter JavaScript Object Properties?

Enumerate Properties of JavaScript Objects

In JavaScript, objects are used to store data as key-value pairs. To retrieve the properties of an object, the for…in loop can be utilized.

Basic Enumeration

const myObject = {
  name: 'Alice',
  age: 25,
  occupation: 'Software Engineer'
};

for (const propertyName in myObject) {
  console.log(propertyName); // Prints: name, age, occupation
  console.log(myObject[propertyName]); // Prints: Alice, 25, Software Engineer
}
Copy after login

Filtering Inherited Properties

By default, the for…in loop also iterates over inherited properties. To filter out inherited properties, the hasOwnProperty() method can be used.

for (const propertyName in myObject) {
  if (myObject.hasOwnProperty(propertyName)) {
    console.log(propertyName); // Prints: name, age, occupation
    console.log(myObject[propertyName]); // Prints: Alice, 25, Software Engineer
  }
}
Copy after login

Considerations

  • Private variables are not accessible using the above methods.
  • If properties are added or modified dynamically, the results of the enumeration may change.
  • It's important to consider the purpose of the enumeration before filtering inherited properties.

The above is the detailed content of How Do I Enumerate and Filter JavaScript Object Properties?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template