How to Loop Through Objects in JavaScript

JavaScript objects are collections of key-value pairs. Sometimes, you need to loop through these objects to access their properties or perform operations on them. In this article, we’ll explore different ways to loop through JavaScript objects and provide examples to help you understand each method.

Understanding JavaScript Objects

A JavaScript object is a data structure that holds key-value pairs. For example:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

In this object, name, age, and city are keys, and their respective values are 'John', 30, and 'New York'.

Methods to Loop Through Objects

There are several ways to loop through objects in JavaScript. Let’s look at the most common methods.

1. Using a for...in Loop

The for...in loop iterates over the enumerable properties of an object. Here’s an example:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

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

Output:

name: John
age: 30
city: New York

2. Using Object.keys()

The Object.keys() method returns an array of an object’s own enumerable property keys. You can then loop through this array:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const keys = Object.keys(person);

for (let i = 0; i < keys.length; i++) {
  const key = keys[i];
  console.log(key + ': ' + person[key]);
}

Output:

name: John
age: 30
city: New York

3. Using Object.values()

The Object.values() method returns an array of an object’s own enumerable property values. Here’s how to use it:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const values = Object.values(person);

for (let i = 0; i < values.length; i++) {
  console.log(values[i]);
}

Output:

John
30
New York

4. Using Object.entries()

The Object.entries() method returns an array of an object’s own enumerable property key-value pairs. Here’s an example:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const entries = Object.entries(person);

for (let i = 0; i < entries.length; i++) {
  const [key, value] = entries[i];
  console.log(key + ': ' + value);
}

Output:

name: John
age: 30
city: New York

Example Scenarios

Scenario 1: Simple Object Iteration

Suppose you have an object representing student grades:

const grades = {
  alice: 85,
  bob: 92,
  charlie: 78
};

for (const student in grades) {
  console.log(`${student} scored ${grades[student]} points.`);
}

Output:

alice scored 85 points.
bob scored 92 points.
charlie scored 78 points.

Scenario 2: Nested Objects

If your object is nested, you can loop through it using nested for...in loops:

const person = {
  name: {
    first: 'John',
    last: 'Doe'
  },
  age: 30,
  city: 'New York'
};

for (const key in person) {
  if (typeof person[key] === 'object') {
    for (const nestedKey in person[key]) {
      console.log(`${key}.${nestedKey}: ${person[key][nestedKey]}`);
    }
  } else {
    console.log(`${key}: ${person[key]}`);
  }
}

Output:

name.first: John
name.last: Doe
age: 30
city: New York

Scenario 3: Filtering and Transforming Data

You can combine object iteration with filtering and transformation operations. For example, filtering out properties with values above a certain threshold:

const scores = {
  game1: 100,
  game2: 85,
  game3: 95,
  game4: 75
};

const highScores = {};

for (const game in scores) {
  if (scores[game] >= 90) {
    highScores[game] = scores[game];
  }
}

console.log(highScores);

Output:

{ game1: 100, game3: 95 }

Frequently Asked Questions

Q1: What is the difference between for...in and for...of?

  • for...in is used to loop over the keys of an object or the indices of an array.
  • for...of is used to loop over the values of an iterable (like arrays, strings, maps, etc.).

Q2: Can I loop through an object in a specific order?

Yes, you can sort the keys before iterating:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const keys = Object.keys(person).sort();

for (const key of keys) {
  console.log(key + ': ' + person[key]);
}

Output:

age: 30
city: New York
name: John

Q3: How do I loop through an object and modify it during iteration?

You can modify the object during iteration, but be cautious as it might lead to unexpected behavior. Here’s an example:

let obj = { a: 1, b: 2 };

for (let key in obj) {
  obj[key + 'New'] = obj[key] * 2;
}

console.log(obj);

Output:

{ a: 1, b: 2, aNew: 2, bNew: 4 }

Q4: What if an object has inherited properties?

The for...in loop includes inherited properties by default. To include only own properties, use Object.prototype.hasOwnProperty.call():

const obj = { a: 1 };
obj.prototype = { b: 2 };

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

Output:

a: 1

Q5: How do I loop through an object and collect the values into an array?

Use Object.values():

const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj);
console.log(values); // [1, 2, 3]

Conclusion

Looping through objects in JavaScript can be done using several methods, each with its own use case. The for...in loop is versatile for iterating over keys, while Object.keys(), Object.values(), and Object.entries() provide more control over the iteration process. By understanding these methods, you can efficiently manipulate and extract data from objects in your JavaScript applications.

Index
Scroll to Top