Yogesh Chauhan's Blog

Solution to “TypeError: ‘x’ is not iterable” in Angular 9

in Angular on October 10, 2020

The TypeScript exception “is not iterable” occurs when the value which is given as the right hand-side of for…of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object.

What went wrong?

The value which is given as the right hand-side of for…of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object.  

An iterable can be a built-in iterable type such as Array, String or Map, a generator result, or an object implementing the iterable protocol.

How to iterate over Object properties

In TypeScript (like JavaScript), Objects are not iterable unless they implement the iterable protocol.

Therefore, you cannot use for…of to iterate over the properties of an object.


//Wrong way of iterating

var obj = { 'France': 'Paris', 'England': 'London' };
for (let p of obj) { // TypeError: obj is not iterable
    // …
}

Instead you have to use Object.keys or Object.entries, to iterate over the properties or entries of an object.


//CORRECT way of iterating

var obj = { 'France': 'Paris', 'England': 'London' };
// Iterate over the property names:
for (let country of Object.keys(obj)) {
    var capital = obj[country];
    console.log(country, capital);
}

for (const [country, capital] of Object.entries(obj))
    console.log(country, capital);

Credit: MDN Docs


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to convert datetime to date format in JavaScript?JavaScriptHow to Access a Global Variable From Inside a Function in PHP?PHPEffects in ReactReactHow to add and remove list items using JavaScript?JavaScriptHow to create and store JSON objects in localStorage using JavaScript?JavaScriptWordPress: How to loop through ACF group fields?WordPress