Looping Through Objects

Objects in JavaScript hold key-value pairs, and sometimes you’ll want to look through all the keys, values, or both. Whether you're displaying user data or processing settings, looping through an object helps you work with everything inside it. JavaScript gives you several ways to loop through objects in a clear and simple way.

Using for...in

The for...in loop is made for looping through object keys.

javascript
1
2
3
4
5
6
          let user = { name: 'Alice', age: 25, city: 'Paris' };

for (let key in user) {
  console.log(key);        // name, age, city
  console.log(user[key]);  // Alice, 25, Paris
}
        

You get each property name as key, and you can access the value with user[key].

Note: This loop also includes keys inherited from the prototype. To avoid that, use hasOwnProperty():

javascript
1
2
3
4
5
          for (let key in user) {
  if (user.hasOwnProperty(key)) {
    console.log(key + ': ' + user[key]);
  }
}
        

Object.keys(), Object.values(), Object.entries()

These built-in methods let you get arrays from objects:

  • Object.keys(obj) returns an array of keys.
  • Object.values(obj) returns an array of values.
  • Object.entries(obj) returns an array of [key, value] pairs.

You can use them with forEach() or a for...of loop:

javascript
1
2
3
4
5
6
7
8
9
10
11
          Object.keys(user).forEach((key) => {
  console.log(key);         // name, age, city
});

Object.values(user).forEach((value) => {
  console.log(value);       // Alice, 25, Paris
});

for (let [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}
        

These methods are useful when you want more control, filtering, or chaining with other array methods like map() or filter().

Looping with Object methods and arrays

Using object methods gives you more power. For example, you can sort values or filter based on certain rules:

javascript
1
2
          let filtered = Object.entries(user).filter(([key, value]) => typeof value === 'string');
console.log(filtered); // Only string values like 'Alice' and 'Paris'
        

This lets you work with object data in a flexible and clean way.