Yandex

JavaScript Iterating Over Objects
Keys, Values, and Entries Explained



JavaScript Iterating Over Objects

Objects in JavaScript are dynamic collections of key-value pairs. Iterating over them allows us to access and manipulate each property efficiently. Whether you're reading data, transforming it, or simply logging values, learning how to loop through objects is foundational to mastering JavaScript.

1. Using for...in Loop

The for...in loop is a traditional way to iterate over all enumerable properties of an object.


const person = {
  name: "Alice",
  age: 30,
  city: "New York"
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}
name: Alice
age: 30
city: New York

Explanation:

The loop variable key takes on each property name in the object. We use person[key] to get its corresponding value. This approach is simple and works for most use cases, but it also includes inherited properties. To avoid that:


for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key + ": " + person[key]);
  }
}

2. Using Object.keys()

Object.keys() returns an array of an object's own enumerable property names (keys). You can then loop using forEach or a for loop.


Object.keys(person).forEach(function(key) {
  console.log(key + ": " + person[key]);
});
name: Alice
age: 30
city: New York

3. Using Object.values()

Object.values() returns an array of the object’s values. This is helpful when you only need the data, not the keys.


Object.values(person).forEach(function(value) {
  console.log(value);
});
Alice
30
New York

4. Using Object.entries()

Object.entries() returns an array of [key, value] pairs. It provides both pieces of the puzzle at once and is ideal for use with destructuring.


for (const [key, value] of Object.entries(person)) {
  console.log(`${key}: ${value}`);
}
name: Alice
age: 30
city: New York

5. Iterating Over Nested Objects

Objects can be nested inside other objects. You'll need to use nested loops or recursion to access all properties.


const user = {
  id: 1,
  name: "John",
  address: {
    city: "Los Angeles",
    zip: "90001"
  }
};

for (let key in user) {
  if (typeof user[key] === "object") {
    for (let nestedKey in user[key]) {
      console.log(nestedKey + ": " + user[key][nestedKey]);
    }
  } else {
    console.log(key + ": " + user[key]);
  }
}
id: 1
name: John
city: Los Angeles
zip: 90001

6. When to Use Which Method?

  • Use for...in when you want to include inherited properties (rarely needed).
  • Use Object.keys() when you only need to work with your object’s own property names.
  • Use Object.values() when only the values matter.
  • Use Object.entries() for looping with both keys and values elegantly.

7. Looping with Object.entries() and map()

You can also transform object entries into new formats using map().


const prices = {
  apple: 1.5,
  banana: 0.9,
  orange: 1.2
};

const updated = Object.entries(prices).map(([fruit, price]) => {
  return `${fruit} costs $${price}`;
});

console.log(updated);
["apple costs $1.5", "banana costs $0.9", "orange costs $1.2"]

8. Using for...of with Object.keys() or Object.entries()

Since for...of works with arrays, you can combine it with Object.keys() or Object.entries() for clean syntax:


for (let key of Object.keys(person)) {
  console.log(`${key} => ${person[key]}`);
}

Conclusion

As a rule of thumb: use the method that best matches the shape of data you’re dealing with and the clarity of expression you want in your code.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M