• Home
  • How do I loop through or enumerate a JavaScript object?

How do I loop through or enumerate a JavaScript object?

There are several ways to loop through or enumerate the properties of an object in JavaScript:

  1. Use a for...in loop: The for...in loop iterates over the enumerable properties of an object, and allows you to access the property names and values.
const object = {a: 1, b: 2, c: 3};

for (const property in object) {
console.log(property, object[property]);
}

This will output the following:

a 1
b 2
c 3
  1. Use Object.keys() and a for loop: The Object.keys() function returns an array of the enumerable property names of an object, which you can then iterate over using a for loop.
const object = {a: 1, b: 2, c: 3};
const keys = Object.keys(object);

for (let i = 0; i < keys.length; i++) {
console.log(keys[i], object[keys[i]]);
}

This will output the same result as the for...in loop above.

  1. Use Object.entries() and a for...of loop: The Object.entries() function returns an array of arrays, where each inner array consists of a property name and a property value. You can iterate over this array using a for...of loop.
const object = {a: 1, b: 2, c: 3};

for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}

This will also output the same result as the previous examples.

  1. Use Object.getOwnPropertyNames() and a for loop: The Object.getOwnPropertyNames() function returns an array of all own (non-inherited) properties of an object, including non-enumerable properties. You can iterate over this array using a for loop.