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 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())}
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 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())})
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.