Skip to content
Advertisement

How to traverse a typed array?

I have the following class model in my application Angular:

JavaScript

And my Controller:

JavaScript

In the template I have a multiple select where I fill an array with the id’s of the chosen categories.

JavaScript

Problem, I’m using ngModel to link the form with the controler, but to send the pre-filled data to the API, I have to format the id’s to the model format, that is:

JavaScript

I try to format the data as follows in the onSubmit() method:

JavaScript

But I get the error:

TypeError: Cannot set property ‘id’ of undefined @ undefined:undefined

How could you be formatting the itemCategories to be able to send the data correctly to the API?

Advertisement

Answer

Use forEach to iterate instead of for loop.

JavaScript

Since your selectedCategories object is an array of numbers, it doesn’t have id property in it. That’s why you’re getting errors.

Working demo at StackBlitz.

Click the button and check the console log.

Advertisement