OneBite.Dev - Coding blog in a bite size

loop object in Javascript

Code snippet on how to loop object in Javascript

for (let key in object) {
  const value = object[key];
  // code here to use key and value
}

This code loops through an object, with the variable ‘key’ representing each property name and ‘value’ representing its corresponding value. In the example, the variable ‘object’ holds the object the code is looping through.

First, the code declares a variable ‘key’ and declares a loop which will execute for each property in the object.

Inside the loop, the code creates a variable called ‘value’ and sets it to the value of the corresponding property in the object.

Finally, the code can contain any code to use the property key and value. For example, this might include console logging each property and value, or assigning each property a new value, or performing a calculation on each value.

javascript