How to iterate over object keys in Javascript


To iterate over object keys in JavaScript, you can use a for..in loop. The for..in loop iterates over all the enumerable properties of an object, including inherited enumerable properties from the object’s prototype chain.

Here’s an example code snippet to iterate over object keys:

const obj = {
  name: "John",
  age: 30,
  address: "123 Main St"
};

for (let key in obj) {
  console.log(key + ": " + obj[key]);
}
name: John
age: 30
address: 123 Main St

Note that the order of iteration is not guaranteed, and you should not rely on it. If you need to iterate over object keys in a specific order, you may need to use an array of keys and sort it accordingly.

Using ES6:

Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});