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);
      });
  }

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

can I you made it like this answer var result = arr.map(person => ({ value: person.id, text: person.name }));
That means you want to get a list of objects instead of a list of RowItems?
I just want a better performance instead of using for loop or 3 maps but rowitems
Because you have to. I see no logical possibility to avoid that.
@amorenew and "3 maps" is a problem because... ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.