Not able to iterate through my object using for of loop over an object

Viewed 91

I'm trying to iterate through an object but getting an error

const myObj = {
  number1: 4,
  number2: 10
}
for (const key of myObj) {
  console.log(`${key}: ${myObj[key]}`);
}

but instead getting a console error

5 Answers

You are actually making a very minor mistake. You are creating an object and using for.. of for that but for..of is use to iterate over an array. Use for..in instead which iterates over an object keys.

Here's your working demo:

const myObj = {
  number1: 4,
  number2: 10
}
    for (const key in myObj) {
  console.log(`${key}: ${myObj[key]}`);
}

Use for..in instead of for..of.

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

Try below.

const myObj = {
  number1: 4,
  number2: 10
}
for (const key in myObj) {
  console.log(`${key}: ${myObj[key]}`);
}

Replace of with in

for...of is used in String, Array, array-like objects.

Whereas in is an operator that returns true if the specified property is in the specified object.

const myObj = {
  number1: 4,
  number2: 10
}
for (const key in myObj) {
  console.log(`${key}: ${myObj[key]}`);
}

Your Error is using for ... of instead of for... in in your loop. To iterate through object I think that using Object methods is better to process your data:

Object.entries(myObj2).forEach(([key, value]) => console.log(key, value))

You can also use keys method that gives you only the key and values that gives you only the values.

Here's good variant, this works perfect:

const myObj = {
  number1: 4,
  number2: 10,
};

Object.keys(myObj).forEach((key) => {
  console.log(`${key}: ${myObj[key]}`);
});
Related