JavaScript Object Iterations
Learn different ways to loop through objects
🔄 What is Object Iteration?
Object iteration means going through each property in an object one by one. Unlike arrays, objects don't have a built-in order, but we have several ways to loop through them!
let person = {name: "Alice", age: 25, city: "New York"};
// We want to access each property: name, age, city
Object Iteration Methods
for...in Loop
Loop through all enumerable properties
for (let key in obj) {
console.log(key, obj[key]);
}
Object.keys()
Get array of property names
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
});
Object.values()
Get array of property values
Object.values(obj).forEach(value => {
console.log(value);
});
Object.entries()
Get array of [key, value] pairs
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
🔹 for...in Loop
The most basic way to iterate through object properties:
let student = {
name: "Emma",
age: 20,
grade: "A",
subject: "Computer Science"
};
console.log("Using for...in loop:");
for (let property in student) {
console.log(property + ": " + student[property]);
}
// Only iterate through own properties (not inherited)
console.log("\nOwn properties only:");
for (let property in student) {
if (student.hasOwnProperty(property)) {
console.log(property + ": " + student[property]);
}
}
Output:
Using for...in loop:
name: Emma
age: 20
grade: A
subject: Computer Science
Own properties only:
name: Emma
age: 20
grade: A
subject: Computer Science
🔹 Object.keys() Method
Get an array of all property names, then iterate:
let car = {
brand: "Toyota",
model: "Camry",
year: 2022,
color: "Blue"
};
// Get all keys
let keys = Object.keys(car);
console.log("Keys:", keys);
// Iterate using forEach
console.log("\nUsing Object.keys() with forEach:");
Object.keys(car).forEach(function(key) {
console.log(key + " -> " + car[key]);
});
// Using for loop
console.log("\nUsing Object.keys() with for loop:");
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
console.log(key + " = " + car[key]);
}
Output:
Keys: ["brand", "model", "year", "color"]
Using Object.keys() with forEach:
brand -> Toyota
model -> Camry
year -> 2022
color -> Blue
Using Object.keys() with for loop:
brand = Toyota
model = Camry
year = 2022
color = Blue
🔹 Object.values() Method
Get an array of all property values:
let book = {
title: "JavaScript Guide",
author: "John Doe",
pages: 350,
published: true
};
// Get all values
let values = Object.values(book);
console.log("Values:", values);
// Iterate through values
console.log("\nIterating through values:");
Object.values(book).forEach(function(value, index) {
console.log("Value " + (index + 1) + ": " + value);
});
// Find specific values
console.log("\nChecking values:");
console.log("Has pages over 300?", Object.values(book).some(val => val > 300));
console.log("All values are truthy?", Object.values(book).every(val => val));
Output:
Values: ["JavaScript Guide", "John Doe", 350, true]
Iterating through values:
Value 1: JavaScript Guide
Value 2: John Doe
Value 3: 350
Value 4: true
Checking values:
Has pages over 300? true
All values are truthy? true
🔹 Object.entries() Method
Get an array of [key, value] pairs - the most powerful method:
let product = {
name: "Laptop",
price: 999,
category: "Electronics",
inStock: true
};
// Get all entries
let entries = Object.entries(product);
console.log("Entries:", entries);
// Iterate using destructuring
console.log("\nUsing destructuring:");
Object.entries(product).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// Convert back to object
console.log("\nConverting back to object:");
let newObj = Object.fromEntries(entries);
console.log(newObj);
// Filter and transform
console.log("\nFiltered entries (only strings):");
Object.entries(product)
.filter(([key, value]) => typeof value === 'string')
.forEach(([key, value]) => {
console.log(`${key} = "${value}"`);
});
Output:
Entries: [["name", "Laptop"], ["price", 999], ["category", "Electronics"], ["inStock", true]]
Using destructuring:
name: Laptop
price: 999
category: Electronics
inStock: true
Converting back to object:
{name: "Laptop", price: 999, category: "Electronics", inStock: true}
Filtered entries (only strings):
name = "Laptop"
category = "Electronics"
🔹 Practical Examples
Real-world scenarios for object iteration:
// Example 1: Count properties
let user = {name: "Bob", email: "[email protected]", age: 30};
let propertyCount = Object.keys(user).length;
console.log("User has " + propertyCount + " properties");
// Example 2: Find property by value
function findKeyByValue(obj, searchValue) {
for (let [key, value] of Object.entries(obj)) {
if (value === searchValue) {
return key;
}
}
return null;
}
let colors = {sky: "blue", grass: "green", sun: "yellow"};
console.log("Key for 'green':", findKeyByValue(colors, "green"));
// Example 3: Transform object
let prices = {apple: 1.2, banana: 0.8, orange: 1.5};
let discountedPrices = {};
Object.entries(prices).forEach(([item, price]) => {
discountedPrices[item] = (price * 0.9).toFixed(2); // 10% discount
});
console.log("Original prices:", prices);
console.log("Discounted prices:", discountedPrices);
Output:
User has 3 properties
Key for 'green': grass
Original prices: {apple: 1.2, banana: 0.8, orange: 1.5}
Discounted prices: {apple: "1.08", banana: "0.72", orange: "1.35"}