map

signature: map(project: Function, thisArg: any): Observable

Apply projection with each value from source.

map - 图1

Examples

Example 1: Add 10 to each number

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { map } from 'rxjs/operators';
  3. //emit (1,2,3,4,5)
  4. const source = from([1, 2, 3, 4, 5]);
  5. //add 10 to each value
  6. const example = source.pipe(map(val => val + 10));
  7. //output: 11,12,13,14,15
  8. const subscribe = example.subscribe(val => console.log(val));
Example 2: Map to single property

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { map } from 'rxjs/operators';
  3. //emit ({name: 'Joe', age: 30}, {name: 'Frank', age: 20},{name: 'Ryan', age: 50})
  4. const source = from([
  5. { name: 'Joe', age: 30 },
  6. { name: 'Frank', age: 20 },
  7. { name: 'Ryan', age: 50 }
  8. ]);
  9. //grab each persons name, could also use pluck for this scenario
  10. const example = source.pipe(map(({ name }) => name));
  11. //output: "Joe","Frank","Ryan"
  12. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/map.ts