skip to content

map vs pluck

 

map operator can be easily substituted with a simple pluck, if all we need is to read a property of a value:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const { rxObserver } = require('api/v0.3');
const { of } = require('rxjs');
const { pluck, map } = require('rxjs/operators');

const source$ = of(
  { a: 1 },
  { a: 2 },
  { },
  { a: 3 }
);

source$
  .pipe(
    map(x => x.a)
  )
  .subscribe(rxObserver('map(x => x.a)'));

source$
  .pipe(
    pluck('a')
  )
  .subscribe(rxObserver(`pluck('a')`));

0msmap(x => x.a)startcomplete11 22 undefinedundefined 33 pluck('a')startcomplete11 22 undefinedundefined 33

Even better when we have nested properties!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const { rxObserver } = require('api/v0.3');
const { of } = require('rxjs');
const { pluck, map } = require('rxjs/operators');

const source$ = of(
  { a: { b: 1 } },
  { a: { b: 2 } },
  { },
  { a: { b: 3 } },
);

source$
  .pipe(
    map(x => x.a && x.a.b)
  )
  .subscribe(rxObserver('map(x => x.a && x.a.b)'));

source$
  .pipe(
    pluck('a', 'b')
  )
  .subscribe(rxObserver(`pluck('a', 'b')`));

0msmap(x => x.a && x.a.b)startcomplete11 22 undefinedundefined 33 pluck('a', 'b')startcomplete11 22 undefinedundefined 33

Read more about pluck vs map comparison in this article: "RxJs|Pluck: A pound of pluck is worth a ton of map !" by chebbi lamis