dots Created with Sketch.
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

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
PHP arrays for US states’ full names and abbreviationsPHPWhat Is a Graph Database?MiscellaneousHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresHow to include CSS and JavaScript files in your WordPress plugin?WordPressHow to refresh a page using PHP at regularly occurring intervals?PHPAngular 9 time clock update every minute, second, hourAngular