亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何篩選僅等于數組中項的映射

如何篩選僅等于數組中項的映射

開心每一天1111 2022-08-27 14:51:07
你好,伙計們,我有一張這樣的地圖Map {'708335088638754946' => 38772,'712747381346795670' => 12051,'712747409108762694' => 12792 }我有一個數組,如let array = ["712747381346795670", "708335088638754946"]如何過濾僅等于數組中項的映射
查看完整描述

4 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

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


查看完整回答
反對 回復 2022-08-27
?
一只斗牛犬

TA貢獻1784條經驗 獲得超2個贊

您可以按如下方式將該函數與該函數一起使用:Object.entriesArray.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);

另一種方法可能是函數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);

使用對象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"));


查看完整回答
反對 回復 2022-08-27
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

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

  }

}


查看完整回答
反對 回復 2022-08-27
?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

您可以只循環訪問所有條目,只將匹配的條目添加到結果中:


const result = new Map();

const array = ["712747381346795670", "708335088638754946"];

for( const [ key, value ] of input.entries() ) {

  if( array.includes( key ) ) {

    result.set( key, value );

  }

}


查看完整回答
反對 回復 2022-08-27
  • 4 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號