3 回答
![?](http://img1.sycdn.imooc.com/54584c5e0001491102200220-100-100.jpg)
TA贡献1796条经验 获得超7个赞
在这个相当人为的示例中,您只想在末尾添加一个 reduce 运算符:
from(people)
.pipe(
groupBy(
person => person.age,
p => p
),
mergeMap(group => zip(of(group.key), group.pipe(toArray()))),
reduce((acc, v) => {
acc.set(v[0], v[1])
return acc
}, new Map<number, any>())
)
.subscribe(m => mapOfPeople = m);
![?](http://img1.sycdn.imooc.com/54584f9d0001219b02200220-100-100.jpg)
TA贡献1804条经验 获得超8个赞
我无法编译您的初始代码,而且我不确定 zip 部分在这种情况下的用途。
一种方法是使用订阅函数处理程序。目前它是 console.log - 但你可以在这里做任何格式的事情(arg) => void(一个从 observable 中获取一个项目并以某种方式处理它的函数。
这是一个将每个年龄段的人的数组添加到地图中的示例:
type Person = { name: string, age: number};
const mapOfPeople = new Map<number, Person[]>();
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),
mergeMap(group => group.pipe(toArray()))
).subscribe(people => {
// the age of any in this group of people is the key
const { age } = people[0];
// set as map's value for this age
mapOfPeople.set(age, people);
});
![?](http://img1.sycdn.imooc.com/533e4d510001c2ad02000200-100-100.jpg)
TA贡献1811条经验 获得超6个赞
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*/)
添加回答
举报