RxJs|Pluck: A pound of pluck is worth a ton of map !
Introduction
Our goal today is to get familiar with the pluck operator and learn in which scenarios it should be used instead of the map operator.
Map vs Pluck operators
The map operator is used to apply a given function to each value emitted by the source Observable. Below an example:
However, if you only want to pick one of the nested properties of every emitted object, a far better choice is the pluck operator !
Given the last example, let’s pick only the band’s name from the emitted object:
Now let’s pick the hit’s title of the best-selling album:
As you may have noticed, you can provide one or many properties to the pluck operator. Many properties are provided if you want to pick a nested object’s property. In the previous example pluck will traverse the tree looking for bestseller.hit.title and won’t fail if one of the parameters is null, it will return undefined. Cool right 😉 ?
In this case, using map would be kind of a pain (because of the nullability of bestseller), the solution with pluck is less verbose.
Conclusion
This article covered the basics of the pluck operator and what makes it different from the map operator. If you are interested I have made another Angular application using the pluck operator, the implementation is detailed in this article.
Live demo here 🚀.