writingsabout

A

AZRULAZIZ

Software Developer

How to loop around JavaScript object

15 March, 2020

Sometimes, we find ourselves needing to loop around an object to see whether it contains a property we’re looking for or perhaps to look for a null value in one of the properties.


To enumerate an object, the two most common ways I always use are:


  1. The for-in loop

    for (let i in obj) { 
    	console.log(“property:, i)
    	console.log(“value:,  obj[i])
    }

  1. The Object.keys() method

    var arrOfProperties = Object.keys(obj)
    
    // This built-in object method will return an array of properties name that an 	object owns.
    
    // Then we can use a for loop to loop around the returned array if we need to check the value of those properties like this
    
    for (let i = 0; i < arrOfProperties.length; i++) {
    	console.log(“property:, arrOfProperties[i])
    	console.log(“value:, obj[arrOfProperties[i]])
    }

The difference between the two

The for-in loop will loop through all properties in an object including the prototype properties it inherited. While Object.keys() method will only return an array of its own properites.