4

I want to iterate through an array of objects and acces the property values of that iterated object in typescript.

Doing this in c#, it's just a matter of performing a foreach through the array.

In typescript this seems a bit different. We can do a foreach, but we dont have access to 'complete' object, how to do this?

@Input() gridDefinitions: GridColumnDefinition[]   
 public test() {
     for (var def **in** this.gridDefinitions){
       var test = <GridColumnDefinition>this.selectedObject;
       let castedtype = <GridColumnDefinition>def; // this gives an error
    }  
 }

UPDATE: I just ran into the solution. Problems lies in how to iterate through the collection. When using of in stead of in we can access the iterated object. See TypeScript for-in statement

free
  • 153
  • 1
  • 2
  • 18

2 Answers2

6

The for...in construct iterates over the keys of an object. To iterate over the items in an array you need to use for..of

for (var def of this.gridDefinitions){ // def is of the array item type no casting necessary 
    var test = <GridColumnDefinition>this.selectedObject;
} 

You can also use array methods such as forEach/ map/reduce to work with arrays in a manner similar to LINQ if you want.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
2

use foreach and give a type to def

gridDefinitions.forEach((def: GridColumnDefinition) => {
       var test = <GridColumnDefinition>this.selectedObject;
       let castedtype = <GridColumnDefinition>def;
 })
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • 2
    @Fre just a note the type annotation on `def` is unnecessary if `gridDefinitions` is of type `GridColumnDefinition[]`. `gridDefinitions.forEach( def => {...}`) will work as well – Titian Cernicova-Dragomir Jun 26 '18 at 11:34