YogeshChauhan . com

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

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 7 How to disable right click and drag and drop of images using jQuery? May 7 How to render Lists in React? May 7 What’s the difference between variables in CSS and SCSS (Sass)? May 7 How to define variables in SCSS (Sass)? May 7 How to show and hide an element on click in React? May 5 Use inline if to make a shorter conditional syntax in React

You might also like these

How to check if the element exists using JavaScript and jQuery?JavaScriptPagination in CSS with multiple examplesCSSMake sure your links have descriptive textUI/UXThe Difference Between isNaN() Method And isNaN() Function In JavaScriptJavaScriptHow to create a Child Theme in WordPress?WordPressWordPress: How to get field values in Advanced Custom Fields?WordPress