[Fixed] RXJS – Transforming an array of items, with operators

Issue

I’ve been struggling for a few hours, I am trying to grasp more advanced concepts, I thought I could use a reduce operator for this, but I’d like to resort to another opinion.

The following code loops manually through a returned array of items, inside a tap, I’ve used of just to simulate what the observable would emit.

What I’d like to achieve is to remap each object inside arrayItems to have an additional property, and the end result to be an array of objects.

My objective here is to ditch the tap, as I feel there are more efficient ways…

        of([{ foo: 'bar' }, { foo: 'baz' }])
            .pipe(
                tap((arrayItems) => {
                    const arr = [];

                    arrayItems.forEach((item) => {
                        arr.push({
                            ...item,
                            extraProperty: {}
                        });
                    });

                    return of(arr);
                })
            )
            .subscribe();

If anyone can give me a pointer, I’ll be very grateful!

Solution

tap operator doesn’t modify your value. it is done to do side effects. Instead, use map to convert the event:

 of([{ foo: 'bar' }, { foo: 'baz' }])
            .pipe(
                map((arrayItems) => 
                    arrayItems.map((item) => ({
                        ...item,
                        extraProperty: {}
                    })
                );
            )
            .subscribe();

Leave a Reply

(*) Required, Your email will not be published