0

Can I improve my code and replace for-loop by array.map?

I searched and I think I could do that but I didn't find how could I apply that.

This is what I found :

var result = arr.map(person => ({ value: person.id, text: person.name }));

And my code is here:

  public getFlights(): Observable<RowItem[]> {
    return this.http
      .get(this.apiHostFlights)
      .map((res: any) => {
        return <LocationModelItem[]>res.json();
      })
      .map((items: LocationModelItem[]) => {
        var rowItems: RowItem[]=[];
        var cachedLenght = items.length;
        for (var i = 0; i < cachedLenght; i++) {
          rowItems.push(
            new RowItem(i, items[i].name, items[i].img, items[i].category)
          );
        }
        return rowItems;
      })
      .catch((error: any) => {
        return Observable.throw(error.statusText);
      });
  }
amorenew
  • 10,760
  • 10
  • 47
  • 69

1 Answers1

11
 public getFlights(): Observable<RowItem[]> {
    return this.http
      .get(this.apiHostFlights)
      .map((res: any) => {
        return <LocationModelItem[]>res.json();
      })
      .map((items: LocationModelItem[]) => {
        return items.map((item, index) => ({
           index: index,
           name: item.name,
           img: item.img,
           category: item.category)
        }))

      })
      .catch((error: any) => {
        return Observable.throw(error.statusText);
      });
  }

This should do it hopefully

Thomas
  • 2,431
  • 17
  • 22