JavaScript Object Properties Iteration (Live Playground)
Iterating over object properties is a common task in JavaScript programming, as it allows you to access and manipulate data stored in objects. In this tutorial, we will explore different ways to iterate over object properties in JavaScript.
Using for...in
Loop
The for...in
loop is a simple way to iterate over the properties of an object. It iterates over the enumerable properties of the object and assigns the property name to the loop variable.
Example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
};
for (const property in person) {
console.log(`${property}: ${person[property]}`);
}
// Output:
// firstName: John
// lastName: Doe
// age: 30
Using Object.keys()
and forEach()
Object.keys()
returns an array of the object's property names. You can use forEach()
to iterate over this array and access the properties.
Example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
};
Object.keys(person).forEach(property => {
console.log(`${property}: ${person[property]}`);
});
// Output:
// firstName: John
// lastName: Doe
// age: 30
Using Object.entries()
and for...of
Loop
Object.entries()
returns an array of arrays containing the object's property names and values. You can use a for...of
loop to iterate over this array and access both the property names and values.
Example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
};
for (const [property, value] of Object.entries(person)) {
console.log(`${property}: ${value}`);
}
// Output:
// firstName: John
// lastName: Doe
// age: 30
Conclusion
Iterating over object properties in JavaScript is essential for working with objects. By mastering techniques such as the for...in
loop, Object.keys()
, and Object.entries()
, you can efficiently access and manipulate object properties in your programs.