繁体   English   中英

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

[英]How to filter the map only equal to the items in the array

大家好,我有一个像这样的 map

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

我有一个像

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

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

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

const result = new Map();
const array = ["712747381346795670", "708335088638754946"];
for( const [ key, value ] of input.entries() ) {
  if( array.includes( key ) ) {
    result.set( key, value );
  }
}
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
  }
}

您可以将 function Object.entries与 function Array.prototype.map一起使用

 let data = {'708335088638754946': 38772,'712747381346795670': 12051,'712747409108762694': 12792 }; let array = ["712747381346795670", "708335088638754946"]; let result = Object.entries(data).filter(([k]) => array.includes(k)).map(([key,value]) => ({[key]: value})); console.log(result);

另一种方法可能是 function Array.prototype.reduce

 let data = {'708335088638754946': 38772,'712747381346795670': 12051,'712747409108762694': 12792 }; let array = ["712747381346795670", "708335088638754946"]; let result = Object.entries(data).reduce((a, [k, v]) => a.concat(array.includes(k)? {[k]: v}: []), []); console.log(result);

使用 object Map

 let data = new Map([['708335088638754946', 38772],['712747381346795670', 12051], ['712747409108762694', 12792]]); let array = ["712747381346795670", "708335088638754946"]; let result = new Map(Array.from(data.keys()).reduce((a, k) => a.concat(array.includes(k)? [[k, data.get(k)]]: []), [])); console.log(result.has("712747409108762694")); console.log(result.has("708335088638754946")); console.log(result.has("712747381346795670"));

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM