How to loop through objects keys and values in Javascript?

  1. How to loop through objects in JavaScript?
    1. for…in Loop
    2. Object.keys() Method
    3. Object.values() Method
    4. Object.entries() Method

How to loop through objects in JavaScript?

The various methods that can be used to loop through objects in JavaScript are:

  • Using a for…in loop
  • Object.keys method
  • Object.values method
  • Object.entries method

for…in Loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const user = {

name: 'John Doe',

email: '[email protected]',

age: 25,

dob: '08/02/1989',

active: true
};
for (const key in user) {

if (user.hasOwnProperty(key)) {

console.log(`${key}: ${user[key]}`);
}
}

Object.keys() Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const courses = {
java: 10,

javascript: 55,

nodejs: 5,

php: 15
};

// convert object to key's array

const keys = Object.keys(courses);

// print all keys

console.log(keys);

// [ 'java', 'javascript', 'nodejs', 'php' ]

// iterate over object

keys.forEach((key, index) => {
console.log(`${key}: ${courses[key]}`);
});

// java: 10

// javascript: 55

// nodejs: 5

// php: 15

Object.values() Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const animals = {
tiger: 1,

cat: 2,

monkey: 3,

elephant: 4
};

// iterate over object values

Object.values(animals).forEach(val => console.log(val));

// 1
// 2
// 3
// 4

Object.entries() Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const animals = {
tiger: 1,

cat: 2,

monkey: 3,

elephant: 4
};

const entries = Object.entries(animals);
console.log(entries);

// [ [ 'tiger', 1 ],

// [ 'cat', 2 ],

// [ 'monkey', 3 ],

// [ 'elephant', 4 ] ]

To loop over the array returned by Object.entries(), you can either use the for…of loop or the forEach() method as shown below:

1
2
3
4
5
6
7
8
9
10
// `for...of` loop
for (const [key, value] of Object.entries(animals)) {
console.log(`${key}: ${value}`);
}

// `forEach()` method

Object.entries(animals).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});