问题描述
我有一个像下面这样的数据结构,使用秋田状态管理作为可观察到的返回,但是本质上,它与其他任何可观察到的一样,如果在秋田中有更好的方法可以做到这一点,但是任何使用rxjs的指针都是也很棒。
{
title: "Cool project",date: "12-09-2020 15:10:33"
events: [{
id: 1,title: "Beer festival",location: "Paris"
},{
id: 2,title: "Fashion week",location: "dubai"
}]
}
我想对事件的子数组执行某种过滤,并将以下内容作为可观察到的返回给我,
发生了我需要按ID进行过滤的事件,而且还返回了诸如date
等的顶级对象属性
{
title: "Cool project",date: "12-09-2020 15:10:33"
event: {
id: 1,location: "Paris"
}
}
解决方法
您的意思是这样的吗?当然,您应该修改id过滤器。
of({
title: "Cool project",date: "12-09-2020 15:10:33",events: [{
id: 1,title: "Beer festival",location: "Paris"
},{
id: 2,title: "Fashion week",location: "Dubai"
}]
}
).pipe(map((val) => {
const val2: any = {};
val2.title = val.title;
val2.date = val.date;
val2.event = val.events.find((e) => e.id === 1)
return val2
})).subscribe((res) => console.log(res));
,
import { of } from "rxjs";
import { filter,map } from "rxjs/operators";
const sample = {
title: "Cool project",events: [
{
id: 1,location: "Paris"
},{
id: 2,location: "Dubai"
}
]
};
const idToFilter = 1;
const source = of(sample).pipe(
map(res => {
const subArrayElement = res.events.find(event => event.id === idToFilter);
return {
title: res.title,date: res.date,event: subArrayElement
};
})
);
source.subscribe(console.log);
在此处查看工作示例:example