Object iteration means looping through an object's properties to access its keys and values.
1. Example object
const product = {
brand: "Samsung",
price: 25000,
model: "Galaxy M",
color: "Black"
};
This object contains four properties: brand, price, model, and color
2. for...in loop
The for...in loop iterates over an object's enumerable property keys.
const product = {
brand: "Samsung",
price: 25000,
model: "Galaxy M"
};
for (let key in product) {
console.log(key);
}
Output:
brand
price
model
To get both the key and its value:
for (let key in product) {
console.log(key, ":", product[key]);
}
Output :
brand : Samsung
price : 25000
model : Galaxy M
Remember: Use product[key] to access a property's value dynamically.
3. Object.keys()
Returns an array of the object's property names.
const product = {
brand: "Samsung",
price: 25000,
model: "Galaxy M"
};
console.log(Object.keys(product));
Output:
["brand", "price", "model"]
Loop through the keys:
Object.keys(product).forEach(key => {
console.log(key);
});
4. Object.values()
Returns an array of the object's property values.
console.log(Object.values(product));
Output:
["Samsung", 25000, "Galaxy M"]
Loop through the values:
Object.values(product).forEach(value => {
console.log(value);
});
5. Object.entries()
Returns an array of key-value pairs. This is useful when you need both.
console.log(Object.entries(product));
Output:
[
["brand", "Samsung"],
["price", 25000],
["model", "Galaxy M"]
]
Using forEach():
Object.entries(product).forEach(([key, value]) => {
console.log(key, ":", value);
});
Output :
brand : Samsung
price : 25000
model : Galaxy M
Top comments (0)