Ankur
Ankur

Reputation: 187

Apply map operator in RxJS to only part of the Object

I have a response object in the following format:

{
'akey':'avalue',
'bkey':'bvalue',
'ckey':'cvalue',
'arrKey':[{'a':'A','t':1},{'b':'B','t':2},{'c':'C','t':3}]
}

I want to apply the map operator in RxJS to only the elements of 'arrKey'.Something like the below,

this.http.get(url)
.map(res=>res.json())
.map(res['arrKey']=>res['arrKey']['t']=res['arrKey']['t']*2)

which after subscribed to results in

{
'akey':'avalue',
'bkey':'bvalue',
'ckey':'cvalue',
'arrKey':[{'a':'A','t':2},{'b':'B','t':4},{'c':'C','t':6}]
}

Is there a function to apply map to a specific part of object and leave the rest unchanged?

Upvotes: 0

Views: 1135

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191749

It could be as simple as .map(res => res.json()).pluck('arrKey').map(transformFn), but I think what you are asking is that you want to do a transformation on arrKey and also pass all of the other properties. You can just do this as a synchronous logical operation inside of a .map:

.map(res => res.json())
.map(response => {
  response.arrKey = response.arrKey.map(arrKey => ({ ...arrKey, t: arrKey.t * 2 }));
  return response;
});

Upvotes: 2

LLai
LLai

Reputation: 13406

If you expect the full response to be emitted from the map method, then you need to return the entire response, but modify it within the map method.

.map(res => {
    res['arrKey'].forEach(item => {
        item['t'] = item['t'] * 2;
    });
    return res;
});

Upvotes: 2

Related Questions