YogeshChauhan.com
Solution to “TypeError: ‘x’ is not iterable” in Angular 9
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

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS Mar 2 WordPress: How to access first and random row values from a repeater field in ACF? Mar 1 The basics of CSS Box model Feb 27 WordPress: How to display slider repeater fields in ACF? Feb 26 Simple Page Hit Counter in PHP

You might also like these

How to catch .keypress() on body using jQuery?jQueryHow to Recognize an Array in JavaScript?JavaScriptUnderstanding the confusing and handy “This” keyword in JavaScriptJavaScriptOptional arguments, Default parameters and REST parameters in JavaScriptJavaScriptObservation of Human Behavior [Shopping Observation Example]MiscCurrencyPipe in Angular 9 with ExamplesAngular