Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between map and pluck in RxJS?

Tags:

rxjs

I am trying to understand the difference between map and pluck transformational operators in RxJS.

Can anyone help me with this?

like image 654
npat89 Avatar asked Sep 18 '17 20:09

npat89


2 Answers

The docs say

Pluck : Like map, but meant only for picking one of the nested properties of every emitted object.

Therefore, let's say you have

[{ name: 'Joe', age: 30, job: { title: 'Developer', language: 'JavaScript' },
{ name: 'Sarah', age: 35 }]

and you want a list of all job titles.

Using map would be kind of a pain (because of the nullability of job), but with 'pluck' you can write pluck('job', 'title') and it will traverse the tree looking for job.title - and won't fail if job is null.

Example taken from : https://www.learnrxjs.io/operators/transformation/pluck.html

https://jsfiddle.net/btroncone/n592m597/

like image 88
Simon_Weaver Avatar answered Oct 11 '22 22:10

Simon_Weaver


As @mgm87 said, you can perform an operation with map. On the opposite, pluck is just taking a value.

For example, with map you could do something like that:

this.http.get('...some api url to get a user...')
  .map(response => response.json())
  .map(user => user.age > 18 ? 'major': 'minor')
  .do(isMajorOrMinor => console.log(isMajorOrMinor))

So you can manipulate your data down the chain even conditionally.

BUT, for me one of the big differences is that map is typed. Which means if you have some data let say:

interface IUser {
  name: string;
  age: number;
  dogs: IDog[];
}

And you receive at some point a user, from which you want to get his dogs:

user$
  .map(user => user.dogs)
  .do(dogs => ...) // here, you do NOT need to precise (dogs: IDog[]) because Typescript will make a type inference

And that's why I'm always using map even to just "pluck" some data.

like image 22
maxime1992 Avatar answered Oct 11 '22 22:10

maxime1992