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 }
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 } }
Considerations
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!