DEV Community

Sajin Joe J
Sajin Joe J

Posted on

Object Iterations in JavaScript

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"
};
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Output:

brand
price
model
Enter fullscreen mode Exit fullscreen mode

To get both the key and its value:

for (let key in product) {
    console.log(key, ":", product[key]);
}
Enter fullscreen mode Exit fullscreen mode

Output :

brand : Samsung
price : 25000
model : Galaxy M
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Output:

["brand", "price", "model"]
Enter fullscreen mode Exit fullscreen mode

Loop through the keys:

Object.keys(product).forEach(key => {
    console.log(key);
});
Enter fullscreen mode Exit fullscreen mode

4. Object.values()
Returns an array of the object's property values.

console.log(Object.values(product));
Enter fullscreen mode Exit fullscreen mode

Output:

["Samsung", 25000, "Galaxy M"]
Enter fullscreen mode Exit fullscreen mode

Loop through the values:

Object.values(product).forEach(value => {
    console.log(value);
});
Enter fullscreen mode Exit fullscreen mode

5. Object.entries()
Returns an array of key-value pairs. This is useful when you need both.

console.log(Object.entries(product));
Enter fullscreen mode Exit fullscreen mode
Output:
[
    ["brand", "Samsung"],
    ["price", 25000],
    ["model", "Galaxy M"]
]
Enter fullscreen mode Exit fullscreen mode

Using forEach():

Object.entries(product).forEach(([key, value]) => {
    console.log(key, ":", value);
});
Enter fullscreen mode Exit fullscreen mode

Output :

brand : Samsung
price : 25000
model : Galaxy M
Enter fullscreen mode Exit fullscreen mode

Top comments (0)