pluck

签名: pluck(properties: ...args): Observable

选择属性来发出。

pluck - 图1

示例

示例 1: 提取对象属性

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { pluck } from 'rxjs/operators';
  3. const source = from([{ name: 'Joe', age: 30 }, { name: 'Sarah', age: 35 }]);
  4. // 提取 name 属性
  5. const example = source.pipe(pluck('name'));
  6. // 输出: "Joe", "Sarah"
  7. const subscribe = example.subscribe(val => console.log(val));
示例 2: 提取嵌套的属性

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { pluck } from 'rxjs/operators';
  3. const source = from([
  4. { name: 'Joe', age: 30, job: { title: 'Developer', language: 'JavaScript' } },
  5. // 当找不到 job 属性的时候会返回 undefined
  6. { name: 'Sarah', age: 35 }
  7. ]);
  8. // 提取 job 中的 title 属性
  9. const example = source.pipe(pluck('job', 'title'));
  10. // 输出: "Developer" , undefined
  11. const subscribe = example.subscribe(val => console.log(val));

其他资源


:file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/pluck.ts