RxJs looping over returned array

altergothen picture altergothen · Jul 27, 2018 · Viewed 14.4k times · Source

Is there a better way using RxJS operators to loop over an array returned from an observable than this to emit a new individual ListingItem?

onGetItemData(){
this.dataService.getItemData().subscribe((itemData) =>
{
  this.itemDataJSON = itemData;
  this.itemDataJSON.forEach(function (value) {
    let new_listing = new ListingItem(value.label,value.market,value.name);
    console.log(new_listing);
  });
 });
}

The API returns a single array containing the items, so I am unable to use .map to access itemData.name

//-- DataService --// 
getItemData(){
 return this.http.get(this._URL, { headers })
        .pipe(map((res: Listings) => res.items))
}

Answer

CozyAzure picture CozyAzure · Jul 27, 2018

Why don't just pipe a map() ?

this.dataService.getItemData()
    .pipe(
        map(itemData => {
            return itemData.map(value => {
                return new ListingItem(value.label, value.market, value.name);
            })
        })
    )
    .subscribe((listingItem) => {
        console.log(listingItem) // gives an array of listingItem
    });

Note that .map() is a JavaScript's native array function, you will use it to transform the data, by looping over each item of the array

Just for a one-liner:

.pipe(
    map(itemData => itemData.map(value => new ListingItem(value.label, value.market, value.name)))
)