how to loop through an object in javascript – Code Example

In this article we will provide you code to loop through object in javascript. You can use map() or forEach() function to loop through keys of the object. You can then access the values with the help of those keys.

Code Example –

1. Using map()

var obj = {
    "tony": "Ironman", 
    "steve": "Captain America", 
    "bruce": "Hulk", 
    "wanda": "Scarlet Witch"
}

Object.keys(obj).map(ele => {
    console.log(ele + " : " + obj[ele])
})

2. Using forEach()

var obj = {
    "tony": "Ironman", 
    "steve": "Captain America", 
    "bruce": "Hulk", 
    "wanda": "Scarlet Witch"
}

Object.keys(obj).forEach(ele => {
    console.log(ele + " : " + obj[ele])
})

3. Using while() loop –

var obj = {
    "tony": "Ironman", 
    "steve": "Captain America", 
    "bruce": "Hulk", 
    "wanda": "Scarlet Witch"
}

var i = 0
keysArr = Object.keys(obj)
while(i < keysArr.length) {
    console.log(keysArr[i] + " : " + obj[keysArr[i]])
    i++;
}

4. Using for() loop –

var obj = {
    "tony": "Ironman", 
    "steve": "Captain America", 
    "bruce": "Hulk", 
    "wanda": "Scarlet Witch"
}

keysArr = Object.keys(obj)
for(var i=0; i < keysArr.length; i++) {
    console.log(keysArr[i] + " : " + obj[keysArr[i]])
}

Output –

tony: Ironman
steve: Captain America
bruce: Hulk
wanda: Scarlet Witch