Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify array in observable with rxjs, return whole object

I have observable like this:

currentPage: 1
items: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
pageSize: 10
totalItems: 6
totalPages: 1

I'm trying to modify every element in items array, and then return a whole object.

   getAllGifts(): Observable<PagedListDTO<GiftIdeaDTO>> {
    return this.http.get<PagedListDTO<GiftIdeaDTO>>(this.urlAPI + '/GiftIdeas/GetAll').
      pipe(
        map(x => x.items.map
          (y => ({ ...y, imageContentB64: y.imageContentB64 + 'Bob' })))
        ,
        tap(console.log)
      );
  }

but i only get a modified array of items, no currentPage property, page Size etc.

How can i modify items array and return whole object?

like image 385
Owik Avatar asked Dec 17 '25 23:12

Owik


1 Answers

You seem to be already familiar with the usage of spread syntax (...). You could also use it for the outer object before applying the Array#map to the items property.

Try the following

getAllGifts(): Observable<PagedListDTO<GiftIdeaDTO>> {
  return this.http
    .get<PagedListDTO<GiftIdeaDTO>>(this.urlAPI + '/GiftIdeas/GetAll')
    .pipe(
      map(ideas => ({
        ...ideas,                          // retain properties of the outer object
        items: ideas.items.map(item => ({  // adjust the `items` property
          ...item, 
          imageContentB64: item.imageContentB64 + 'Bob' 
        }))
      })),
      tap(console.log)
    );
}
like image 125
ruth Avatar answered Dec 20 '25 11:12

ruth