Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: "[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.

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);
}

Essentially, I am attempting to replicate the functionality of Array.prototype.map() - just on a Map instead of an Array.

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.

like image 904
Andrew Hill Avatar asked Oct 06 '17 12:10

Andrew Hill


People also ask

Can we use filter with map?

Using JavaScript `map()` and `filter()` Together for Composition. JavaScript's Array#map() and Array#filter() functions are great when used together because they allow you to compose simple functions.

What is filter () map () and reduce ()?

Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer (you) to write simpler, shorter code, without neccessarily needing to bother about intricacies like loops and branching.


1 Answers

It is

Array.from(map.values()).filter((item: Event) => item.event_id === eventId);

Or for TypeScript downlevelIteration option,

[...map.values()].filter((item: Event) => item.event_id === eventId);
like image 173
Estus Flask Avatar answered Sep 19 '22 05:09

Estus Flask