How to loop through object values - JavaScript

Mo Ibra

Mo Ibra

Dec 9, 2022

In this article we will learn how to loop through object values.

It is very common to iterate over an object values in JavaScript.

To iterate over objects values we will use Object.values method.

The Object.values() method returns an array of a given object's own enumerable string-keyed property values. (Source: MDN)


Problem

Now we want to iterate over the values of the object.

Imagine you have an object like this:

const myObj = {
    name: "John",
    age: 30,
}

And we want to iterate over the values to give us this output:

John
30

How do you solve that problem?

As we said before, we will use Object.values to solve this problem.


How to iterate over an object values using Object.values method

It takes the object that you want to loop over as an argument and returns an array of values.

Example

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Array of values
const values = Object.values(myObject);

// Print values
console.log(values);

Output

[ 'John', 30 ]

As you can see, it returned an array with all the values, and this means that we can iterate over the array in any way.

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Array of values
const values = Object.values(myObject);

// Iterate over values with `forEach`
values.forEach(value => {
    console.log(value);
});

Output

John
30

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: