javascript

How to use Object.keys in forEach


In this article, you will learn about how to use Object.keys() in forEach.

In JavaScript an Object is a data type that is used to store various types of collection and complex entities. forEach loop is only used on the array. You can not use it to iterate the properties of an Object directly. To do so you have to transform an Object into an array first and you can do it easily by using Object.keys().

Let’s imagine a scenario first. Suppose you have an Student Object where you store student’s name and age. Now by using Object.keys() function you can easily iterate those values. Follow the code example below:

const student = {
  name : 'Deven',
  age : '19'
};

Object.keys(student).forEach(el => {
  console.log(el, student[el]);
});

// Output :
// 'name' 'deven'
// 'age' '19'

Here, when you used Object.keys(student), it will simply return an array of the student object and you know that forEach can iterate the entities of an array. So you can easily get your desired output.

If you want to see the values only then you can use Object.values() function which also returns an array of the Object’s value. See example :

const student = {
  name : 'deven',
  age : '19'
};

Object.values(student).forEach(el => {
  console.log(`${el}`);
});

// Output :
// 'Deven'
// '19

This is all about Object.keys() in javaScript forEach loop. You can get a clear understanding from this article.


Share on social media

//