JavaScript - Iterate over the properties of an object

📋 Table Of Content
In javascript, iterating through the elements of an array is very easy. We have different methods like forEach(), map() and for.. of method to do the task.
However, if we try to loop a JavaScript object using those methods it will give us an error.
For example, let's say we have an object.
const obj = {
name: 'Alex',
city:'New York',
country: 'USA'
}
Now, if we try to iterate the object properties using forEach()
functions.
obj.forEach((e) => console.log(e))
We get "obj.forEach is not a function" error in our console.
And with map()
function.
obj.map((e) => console.log(e))
Here too, we get "obj.map is not a function" error.
And if we try to use the for..of
loop, we get
for (const item of obj) {
console.log(item)
}
We "get the obj is not iterable" error in our console.
So, how can we loop through the properties of an object?
Well, there are two ways to iterate through the properties of a JavaScript object.
- Using for..in loop
- Using Object.entries()
Let's see each with an example.
Using for..in to iterate over the properties of an object
The for..in
loop statement loops over each property in an object in Javascript. It is the most simple way to loop over JavaScript object properties.
Syntax:
for (var item in object) {
code block
}
Example:
const obj = {
name: 'Alex',
city:'New York',
country: 'USA'
}
for (const item in obj) {
console.log(item)
}
Output:
name
city
country
It returns all the keys from the object. However, if you want the values, we can just check for the values corresponding to the keys, like this
for (const item in obj) {
console.log(obj[item])
}
This will return all the values of the properties.
One problem with for..in
loop is that, since objects inherits properties from their prototypes, it loops through those properties too.
So, to avoid it we can use the hasOwnProperty()
method. It will return only those properties which belong to the object directly.
Let's see an example with hasOwnProperty() method
for (const item in obj) {
if (obj.hasOwnProperty(item)){
console.log(item)
}
}
Using Object.entries to iterate over JavaScript object properties
Another option is to use the Object.entries()
method in JavaScript.
The Object.entries()
method returns an array containing all the enumerable propeties of an object.
And we can use map(), forEach(), or for..of statement to loop through the object property array.
Example:
//Using Array.map()
Object.entries(obj).map(item => {
console.log(item)
})
// Using Array.forEach()
Object.entries(obj).forEach(item => {
console.log(item)
})
//Using for..of
for (const item of Object.entries(obj)) {
console.log(item)
}
Here, the object is converted into an array and then looped using map(), forEach(), and for..of loop.