是否可以在 Typescript 中按值“过滤”地图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46605403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to "filter" a Map by value in Typescript?
提问by Andrew Hill
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:
我正在寻找一种按值而不是键过滤地图的方法。我有一个数据集,在我的 Angular 应用程序中建模如下:
{
"85d55e6b-f4bf-47bb-a988-78fdb9650ef0": {
is_deleted: false,
public_email: "[email protected]",
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",
},
}
The keys on these entries are the same as the id
field on the entries values.
这些条目上的键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:
鉴于这些条目中的几个,我想过滤并返回一个new Map()
只包含那些具有给定event_id
. 如果这是一个数组,我只会执行以下操作:
function example(eventId: string): Event[] {
return array.filter((item: Event) => item.event_id === eventId);
}
Essentially, I am attempting to replicate the functionality of Array.prototype.map()
- just on a Map instead of an Array.
本质上,我试图复制的功能Array.prototype.map()
- 只是在地图而不是数组上。
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.
我愿意使用 Lodash,如果它有助于以更简洁的方式实现这一点,因为它已经在我的项目中可用。
回答by Estus Flask
It is
它是
Array.from(map.values()).filter((item: Event) => item.event_id === eventId);
Or for TypeScript downlevelIteration
option,
或者对于 TypeScriptdownlevelIteration
选项,
[...map.values()].filter((item: Event) => item.event_id === eventId);
回答by oreofeolurin
First you need to flatten the map, Then extract the contents to an Events
object
首先需要将地图展平,然后将内容提取到一个Events
对象中
let dataSet = {
"entry1" : { id: "85d55e6b-f4bf-47b0" },
"entry2" : { visitor_id: "6665b-7555bf-978b0" }
}
let flattenedMap = {};
Object.entries(dataSet).forEach(
([key,value]) => Object.assign(flattenedMap, value)
);
console.log("The flattened Map")
console.log(flattenedMap)
let events = [];
Object.entries(flattenedMap).forEach(
([key, value]) => events.push({"event_id" : value})
);
console.log("The events");
console.log(events);