iterate object in javascript

There are several ways to iterate over an object in JavaScript.

Using the for...in loop

One of the most common ways is to use the for...in loop. This loop iterates over the keys of an object and allows you to access the corresponding value.

index.tsx
const obj = { a: 1, b: 2, c: 3 };

for (let key in obj) {
  console.log(key + ": " + obj[key]);
}
98 chars
6 lines

Output:

index.tsx
a: 1
b: 2
c: 3
15 chars
4 lines

Using Object.entries()

Another way to iterate over an object in JavaScript is by using the Object.entries() method. This method returns an array of the object's enumerable property pairs.

index.tsx
const obj = { a: 1, b: 2, c: 3 };

for (let [key, value] of Object.entries(obj)) {
  console.log(key + ": " + value);
}
120 chars
6 lines

Output:

index.tsx
a: 1
b: 2
c: 3
15 chars
4 lines

These are the two most common ways to iterate over an object in JavaScript.

gistlibby LogSnag