Here are 4 ways to loop through an object in JavaScript:
1. for in
The first way is using the for ... in
statement.
The syntax is for (const variable in object) {}
.
variable
can be any name (like key
, prop
, etc), and it represents the key of the current property being iterated.
For example:
const user = {
id: 1,
name: 'Abdu',
age: 22
}
for (const key in user) {
console.log(key, user[key])
}
// id 1
// name Abdu
// age 22
2. Object.keys
The second way is using the Object.keys(object)
method.
This method returns an array containing all the keys in the object.
For example:
const user = {
id: 1,
name: 'Abdu',
age: 22
}
Object
.keys(user) // ['id', 'name', 'age']
.forEach(key => {
console.log(key, user[key])
})
// id 1
// name Abdu
// age 22
3. Object.values()
The third way is using the Object.values(object)
method.
This method returns an array containing all the values in the object.
For example:
const user = {
id: 1,
name: 'Abdu',
age: 22
}
Object
.values(user) // [1, 'Abdu', 22]
.forEach(value => {
console.log(value)
})
// 1
// Abdu
// 22
4. Object.entries
The last way is using the Object.entries(object)
method.
This method returns an array containing all the keys and values in the object.
Each key and value is represented as an array in the form: [key, value]
.
const user = {
id: 1,
name: 'Abdu',
age: 22
}
Object
.entries(user) // [['id', 1], ['name', 'Abdu'], ['age', 22]]
.forEach(([key, value]) => {
console.log(key, value)
})
// id 1
// name Abdu
// age 22
Top comments (1)
Fantastic article — I learned a lot and appreciate the effort you put into this.