开发者问题收集

如何仅过滤地图仅等于数组中的项目

2020-05-21
55

大家好,我有一张这样的地图

Map {
'708335088638754946' => 38772,
'712747381346795670' => 12051,
'712747409108762694' => 12792 
}

我有一个数组,如

let array = ["712747381346795670", "708335088638754946"]

我怎样才能过滤仅等于数组中项目的地图

3个回答

您可以遍历所有条目并仅将匹配的条目添加到结果中:

const result = new Map();
const array = ["712747381346795670", "708335088638754946"];
for( const [ key, value ] of input.entries() ) {
  if( array.includes( key ) ) {
    result.set( key, value );
  }
}
Sirko
2020-05-21
const map = new Map([["a", "b"], ["c", "d"], ["e", "f"]]);
const array = ["a", "c"];
console.log(map);
for (let [prop, value] of map) {
  if (array.includes(prop)) {
    // collect matched items here
  }
}
fengxh
2020-05-21
const oldMap = new Map([["a", "1"], ["b", "2"], ["c", "3"]]);
const array = ["a", "c"];
const newMap = new Map(array.map(key => [key, oldMap.get(key)]));

// newMap is the same as oldMap but only with keys from array

const oldMap = new Map([["a", "1"], ["b", "2"], ["c", "3"]]);
const array = ["a", "c"];
const newMap = new Map([...oldMap.entries()].filter(entry => array.includes(entry[0])))

// newMap is the same as oldMap but only with keys from array
Michal Szorád
2020-05-21