How Can I Iterate Or Loop Through A JavaScript Object In JavaScript?

There are several ways to loop through or enumerate a JavaScript object. Here are a few examples:

  1. for…in loop: This loop iterates over the enumerable properties of an object.
const obj = { a: 1, b: 2, c: 3 };

for (const key in obj) {
  console.log(key, obj[key]);
}
  1. Object.entries(): This method returns an array of an object’s own enumerable string-keyed property [key, value] pairs.
const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj).forEach(([key, value]) => {
  console.log(key, value);
});
  1. Object.keys(): This method returns an array of an object’s own enumerable property names.
const obj = { a: 1, b: 2, c: 3 };

Object.keys(obj).forEach(key => {
  console.log(key, obj[key]);
});
  1. Object.values(): This method returns an array of an object’s own enumerable property values.
const obj = { a: 1, b: 2, c: 3 };

Object.values(obj).forEach(value => {
  console.log(value);
});

Ensure to use the appropriate method based on your specific needs.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!