javascript

How to iterate over an object in Javascript

Iterating over an object in Javascript can be a great way to access data stored within the object. By looping over an object, you can get the specific values of the object keys, which can be a helpful tool when trying to access and manipulate data. In this article, you'll learn how to iterate over an object in Javascript and use it to access the data stored within.

How to iterate over an object in Javascript

Steps to iterate over an object using Javascript

  1. First, get all the keys from the object using Object.keys(my_obj). This will return the key array
  2. Now using the forEach() function iterate over the above array and find the value from the object in each iteration.

Using forEach() loop

const my_obj = {
    "name": "John",
    "city": "New York",
    "profession": "engineer"
};

Object.keys(my_obj).forEach( key => {
    console.log(my_obj[key]);
})

Output

John
New York
engineer

Try it yourself

The above code example uses the Object.keys() method to loop through the properties of the my_obj object. For each property, the value of the property is logged to the console.

The Object.keys(my_obj) method returns the following array:

["name","city","profession"]

We can also use Javascript for loop to iterate over this array and get the value from the object in each iteration.


Using for loop

const my_obj = {
    "name": "John",
    "city": "New York",
    "profession": "engineer"
};

const all_keys = Object.keys(my_obj);

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

Output

John
New York
engineer

Try it yourself

The above code example is used to iterate through an object and output the values of each key. The code begins by declaring a constant named my_obj and assigning it to an object with three properties.

The next line uses the Object.keys() method to return an array of keys from the object and assigns it to a constant named all_keys.

A for loop is then used to loop through the array of keys. Inside the loop, the console.log() method is used to log the value of each key in the object to the console.


Was this helpful?