How to iterate over a JavaScript object
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:
- Using a
forloop - Using a
for-eachloop
Using a for loop
//declare an objectobj = { '1': 'apple','2': 'orange','3': 'grapes','4': 'guava','5': 'watermelon' }//Using for of loop to iteratefor(const [key,value] of Object.entries(obj)){//print key and value pairs//transform the value to uppercaseconsole.log(key,value.toUpperCase())}
Explanation
In the above code snippet:
- Line 2: We declared and initialized an object
obj. - Line 9: We used a
forloop to iterate through thekey-valuepairs returned byObject.entries(obj). - Line 12: We transformed the value to uppercase and printed the key and value pairs of the given object.
Using a for-each loop
//declare an objectobj = { '1': 'apple','2': 'orange','3': 'grapes','4': 'guava','5': 'watermelon' }//Use Object.entries and forEach loop to traverse the objectObject.entries(obj).forEach(([key,value])=>{//print key and value pairs//transform the value to uppercaseconsole.log(key,value.toUpperCase())})
Explanation
In the above code snippet:
- Line 2: We declared and initialized an object
obj. - Line 9: We used a
forEachloop and lambda function to iterate through thekey-valuepairs returned byObject.entries(obj). - Line 10: We destructured the
[key, value]as distinct variables. - Line 13: We transformed the value to uppercase and printed the key and value pairs of the given object.