是否可以在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:56:55  来源:igfitidea点击:

Is it possible to "filter" a Map by value in Typescript?

angulartypescriptecmascript-6lodash

提问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 idfield 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 downlevelIterationoption,

或者对于 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 Eventsobject

首先需要将地图展平,然后将内容提取到一个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);