You can iterate through the properties of a JavaScript object using the following methods:
1. Using Object.keys():
Retrieves an array of keys, which can be iterated using forEach or loops.
Example:
const person = { name: 'Ram', age: 26, city: 'Pune' };
Object.keys(person).forEach(key => {
console.log(`${key}: ${person[key]}`);
});
Output:
name: Ram
age: 26
city: Pune
2. Using Object.entries() (Key-Value Pairs):
Returns an array of key-value pairs, which is useful for direct iteration.
Example:
const person = { name: 'Priya', age: 22, city: 'Delhi' };
Object.entries(person).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Output:
name: Priya
age: 22
city: Delhi