MergeMap 到 Map RxJS 打字稿

我目前正在学习 RxJS,但不明白。我有这段代码:


mapOfPeople = new Map<number, any>();


const people = [

  { name: 'Sue', age: 25 },

  { name: 'Joe', age: 30 },

  { name: 'Frank', age: 25 },

  { name: 'Sarah', age: 35 }

];


from(people)

  .pipe(

    groupBy(

      person => person.age,

      p => p

    ),

    mergeMap(group => zip(of(group.key), group.pipe(toArray())))

  )

  .subscribe(console.log);

此代码来自教程。


我想将输出放入给定的哈希图中。我该如何管理?我不知道。


慕的地10843
浏览 105回答 3
3回答

芜湖不芜

在这个相当人为的示例中,您只想在末尾添加一个 reduce 运算符:from(people)&nbsp; .pipe(&nbsp; &nbsp; groupBy(&nbsp; &nbsp; &nbsp; person => person.age,&nbsp; &nbsp; &nbsp; p => p&nbsp; &nbsp; ),&nbsp; &nbsp; mergeMap(group => zip(of(group.key), group.pipe(toArray()))),&nbsp; &nbsp; reduce((acc, v) => {&nbsp; &nbsp; &nbsp; acc.set(v[0], v[1])&nbsp; &nbsp; &nbsp; return acc&nbsp; &nbsp; }, new Map<number, any>())&nbsp; )&nbsp; .subscribe(m => mapOfPeople = m);

胡说叔叔

我无法编译您的初始代码,而且我不确定 zip 部分在这种情况下的用途。一种方法是使用订阅函数处理程序。目前它是 console.log - 但你可以在这里做任何格式的事情(arg) => void(一个从 observable 中获取一个项目并以某种方式处理它的函数。这是一个将每个年龄段的人的数组添加到地图中的示例:type Person = { name: string, age: number};const mapOfPeople = new Map<number, Person[]>();const people = [&nbsp; { name: 'Sue', age: 25 },&nbsp; { name: 'Joe', age: 30 },&nbsp; { name: 'Frank', age: 25 },&nbsp; { name: 'Sarah', age: 35 }];from(people).pipe(&nbsp; groupBy(person => person.age),&nbsp; mergeMap(group => group.pipe(toArray()))).subscribe(people => {&nbsp; // the age of any in this group of people is the key&nbsp; const { age } = people[0];&nbsp; // set as map's value for this age&nbsp; mapOfPeople.set(age, people);});

杨魅力

mapOfPeople: any;const people = [  { name: 'Sue', age: 25 },  { name: 'Joe', age: 30 },  { name: 'Frank', age: 25 },  { name: 'Sarah', age: 35 }];from(people)  .pipe(    groupBy(      person => person.age,      p => p    ),    mergeMap(group => zip(of(group.key), group.pipe(toArray())))  )  .subscribe(res => mapOfPeople = res /*or do whatever you want with the result*/)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript