In this shot, we will learn how to iterate over a JavaScript object.
The Object.entries
method will return the key-value
pairs for an object that is passed as a parameter to it.
We will try to iterate those returned key-value
pairs using the following methods:
for
loopfor-each
loopfor
loop//declare an object obj = { '1': 'apple', '2': 'orange', '3': 'grapes', '4': 'guava', '5': 'watermelon' } //Using for of loop to iterate for(const [key,value] of Object.entries(obj)){ //print key and value pairs //transform the value to uppercase console.log(key,value.toUpperCase()) }
In the above code snippet:
obj
.for
loop to iterate through the key-value
pairs returned by Object.entries(obj)
.for-each
loop//declare an object obj = { '1': 'apple', '2': 'orange', '3': 'grapes', '4': 'guava', '5': 'watermelon' } //Use Object.entries and forEach loop to traverse the object Object.entries(obj).forEach( ([key,value])=>{ //print key and value pairs //transform the value to uppercase console.log(key,value.toUpperCase()) } )
In the above code snippet:
obj
.forEach
loop and lambda function to iterate through the key-value
pairs returned by Object.entries(obj)
.[key, value]
as distinct variables.RELATED TAGS
CONTRIBUTOR
View all Courses