JavaScript objects are dynamically created by adding properties to them.
Therefore, we may have to loop through its properties with a loop to get the values.
In this article, we’ll look at how to loop through a plain JavaScript object.
Object.keys
The Object.keys
method returns an array of all non-inherited string property keys of an object.
To use it, we can write:
const obj = {
a: 1,
b: 2,
c: 3
}
for (const key of Object.keys(obj)) {
console.log(key, obj[key])
}
We use the for-of loop to loop through the array of keys returned by Object.keys
.
Then we can access the value by passing the key
into the square brackets after obj
.
So we see:
a 1
b 2
c 3
logged.
Object.values
We can just loop through the values of an object with the Object.values
method.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
}
for (const value of Object.values(obj)) {
console.log(value)
}
Object.values
return an array with all the properties values of an object, so we can use the for-of loop to log the property values.
And so we get:
1
2
3
in the console.
Object.entries
Also, we can use the Object.entries
method to return an array with arrays of key-value pairs.
To do this, we can write:
const obj = {
a: 1,
b: 2,
c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(key, value)
}
We destructure the key
and value
from each array entries returned by Object.entries
.
Then we can log them in the loop body.
And we get the same result as we did in the previous example.
Loop Through Nested Objects
To loop through a nested object, we can create a function that calls itself to loop through their properties at each level of the object.
To do this, we write:
const obj = {
a: 1,
b: 2,
c: {
d: {
e: 4
},
f: 5
}
}
const loopNestedObj = obj => {
for (const [key, value] of Object.entries(obj)) {
console.log(key, value)
if (typeof value === 'object' && value !== null) {
loopNestedObj(value)
}
}
}
loopNestedObj(obj)
We create the loopNestedObj
function that takes an obj
object.
Inside the function, we have the same loop as in the previous example.
But we have an if
block to check the value
‘s data type to see if it’s an object.
If it is, then we call loopNestedObj
to loop through its content.
The expression typeof value === ‘object’ && value !== null
is needed to check if value
is an object since typeof null
is also 'object'
.
Therefore, we need both checks to check for an object.
Conclusion
We can traverse an object with the for-of loop and various static object methods provided by JavaScript.