How to traverse a typed array? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to traverse a typed array? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following class model in my application Angular:

export class IItemsModel {
  public description: string;
  public itemDetail: IItemDetailModel;
  public itemCategories: IItemCategoriesModel[];  // array of IItemCategoriesModel

export class IItemCategoriesModel {
  public id: string | number;
  public description: string;

And my Controller:

itemModel: IItemsModel;
selectedCategories: any[] = [];

ngOnInit() {
  this.itemModel = new IItemsModel();
  this.itemModel.itemCategories = [];

onSubmit(form: NgForm) {
  // here I format the data

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

[25, 38]  // selectedCategories

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:

  itemDetail: 'something',
  itemCategories: [
    { id: any Id },
    { id: other Id }

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

for(let i=0; i<this.selectedCategories.length; i++) {
  this.itemModel.itemCategories[i].id = this.selectedCategories[i];

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?


Use forEach to iterate instead of for loop.

this.selectedCategories.forEach(f => {
    this.itemModel.itemCategories.push({ id: f, description: '' })

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.

We are here to answer your question about How to traverse a typed array? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji