是否可以在 Typescript 中按值“过滤”Map?

问题描述 投票:0回答:5

我正在寻找一种按值而不是键来过滤地图的方法。我的 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",
  },
}

这些条目上的键与条目值上的

id
字段相同。

给定其中几个条目,我想过滤并返回一个

new Map()
,其中仅包含具有给定
event_id
的条目。如果这是一个数组,我只需执行以下操作:

function example(eventId: string): Event[] {
  return array.filter((item: Event) => item.event_id === eventId);
}

本质上,我正在尝试复制

Array.prototype.map()
的功能 - 只是在地图而不是数组上。

如果 Lodash 有助于以更简洁的方式实现这一目标,我愿意使用它,因为它已经在我的项目中可用。

angular typescript ecmascript-6 lodash
5个回答
51
投票

如果某个键很重要,并且结果需要是一个新的

Map
,那么它是:

new Map(
  [...map.entries()]
  .filter(([key, item]) => item.event_id === eventId)
)

如果键不重要,可以将映射转换为数组:

[...map.values()]
.filter((item: Event) => item.event_id === eventId);
对于没有

Array.from(map.values())
 选项的 TypeScript,应使用 
[...map.values()]
 代替 
downlevelIteration
等。


11
投票

这是将键和值保持在一起的简短语法:

const dict = new Map([["Z", 1324], ["A", 1], ["B", 2], ["C", 3], ["D", -12345]])

const filtered = [...dict.entries()].filter( it => it[1] < 10 ) 

// >  [ [ 'A', 1 ], [ 'B', 2 ], [ 'C', 3 ], [ 'D', -12345 ] ] 

2
投票
export class MapUtils {
  static filter<TKey, TValue>(map: Map<TKey, TValue>, filterFunction: (key: TKey, value: TValue) => boolean): Map<TKey, TValue> {
    const filteredMap: Map<TKey, TValue> = new Map<TKey, TValue>();
    
    map.forEach((value, key) => {
      if (filterFunction(key, value)) {
        filteredMap.set(key, value);
      }
    });
    
    return filteredMap;
  }
}

用途:

 const filteredMap = MapUtils.filter(map, (key, value) => value > 0)

0
投票

这个使用

Object.entries
将地图转换为数组,并使用
Object.fromEntries
转换回地图。

let qs = {a:'A 1',b:null,c:'C 3'};
let qsfiltered = Object.fromEntries(
    Object.entries(qs).filter(([k,v]) => v !== null)
);

console.log(JSON.stringify(qsfiltered));

-1
投票

首先需要展平地图,然后将内容提取到

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

© www.soinside.com 2019 - 2025. All rights reserved.