how to use the pluck function from the rxjs library in javascript

The pluck function in rxjs is used to extract a specific property (or nested property) from each source object in a stream of data. Here's an example of how to use pluck:

index.tsx
const { from } = rxjs;
const { pluck } = rxjs.operators;

const data = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 }
];

const source$ = from(data);

// Extract only the "name" property from each object
const name$ = source$.pipe(pluck('name'));

// Extract the "id" and "age" properties from each object
const idAge$ = source$.pipe(pluck('id', 'age'));

// Subscribe to the streams to see the extracted properties
name$.subscribe(name => console.log(name)); // "Alice", "Bob", "Charlie"
idAge$.subscribe(({id, age}) => console.log(id, age)); // "1 25", "2 30", "3 35"
635 chars
21 lines

In this example, we create an observable source$ from an array of data. We then use the pluck operator to extract the "name" property from each object in the source$ stream, and also extract the "id" and "age" properties from each object. Finally, we subscribe to the resulting streams (name$ and idAge$) to see the extracted values.

gistlibby LogSnag