是否有可能对过滤器进行“过滤"按打字稿中的值映射? [英] Is it possible to "filter" a Map by value in Typescript?
问题描述
我正在寻找一种通过值而不是键来过滤地图的方法.我的Angular应用程序中有一个数据模型如下:
I am looking for a way to filter a map by value instead of key. I have a data set that is modeled as follows in my Angular application:
{
"85d55e6b-f4bf-47bb-a988-78fdb9650ef0": {
is_deleted: false,
public_email: "007@example.org",
id: "85d55e6b-f4bf-47bb-a988-78fdb9650ef0",
modified_at: "2017-09-26T15:35:06.853492Z",
social_url: "https://facebook.com/jamesbond007",
event_id: "213b01de-da9e-4d19-8e9c-c0dae63e019c",
visitor_id: "c3c232ff-1381-4776-a7f2-46c177ecde1c",
},
}
这些条目上的键与条目值上的id
字段相同.
The keys on these entries are the same as the id
field on the entries values.
给出几个这样的条目,我想过滤并返回一个new Map()
,该new Map()
仅包含具有给定event_id
的那些条目.如果这是一个数组,我将执行以下操作:
Given several of these entries, I would like to filter and return a new Map()
that contains only those entries with a given event_id
. Were this an array I would just do the following:
function example(eventId: string): Event[] {
return array.filter((item: Event) => item.event_id === eventId);
}
本质上,我试图复制Array.prototype.map()
的功能-仅在Map而不是Array上.
Essentially, I am attempting to replicate the functionality of Array.prototype.map()
- just on a Map instead of an Array.
我愿意使用Lodash,因为它可以帮助我以更简洁的方式实现此目的,因为它已经在我的项目中提供了.
I am willing to use Lodash if it will help achieve this in a more succinct way as it is already available in my project.
推荐答案
是
Array.from(map.values()).filter((item: Event) => item.event_id === eventId);
或者对于TypeScript downlevelIteration
选项
Or for TypeScript downlevelIteration
option,
[...map.values()].filter((item: Event) => item.event_id === eventId);
这篇关于是否有可能对过滤器进行“过滤"按打字稿中的值映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!