Iterate over the keys in an object using Object.keys()

July 15, 2022  ‐ 1 min read

An easy way to loop over the keys in a JavaScript object is by extracting out the keys as an array using Object.keys().

After doing so we can loop over the result as a regular array.

const keys = Object.keys({ a: 0, b: 1, c: 2 });
//=> (3) ['a', 'b', 'c']

for (const key of keys) {
  //
}

Besides the approach above we can directly loop over key value pairs in an object as well.

const obj = { a: 0, b: 1, c: 2 };
for (const [key, value] of Object.entries(obj)) {
  //
}