迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

如何在 JavaScript 中过滤 Map

作者:迹忆客 最近更新:2022/09/10 浏览次数:

使用 forEach() 方法在 JavaScript 中过滤 Map。 使用 Map 中的每个键值对调用该方法,我们可以在其中检查条件并使用 delete() 方法删除我们想要过滤掉的任何 Map 元素。

const map1 = new Map([
  ['num1', 1],
  ['num2', 2],
  ['num3', 3],
]);

map1.forEach((value, key) => {
  if (value > 1) {
    map1.delete(key);
  }
});

// 👇️ {'num1' => 1}
console.log(map1);

我们使用 Map.forEach 方法迭代 Map 对象。

我们传递给 forEach() 方法的函数会为 Map 的每个键值对调用,并传递以下参数:

  • value - 迭代的值
  • key - 迭代的关键
  • map - 地图对象

我们使用 value 来检查条件,并使用 key 来删除 Map 中不需要的任何元素。

另一种方法是将 Map 方法转换为数组并使用 filter 方法。

在 JavaScript 中过滤Map:

  1. 将 Map 转换为数组。
  2. 使用 filter() 方法遍历数组。
  3. 排除不符合条件的元素。
  4. 将数组转换回 Map。
const map1 = new Map([
  ['num1', 1],
  ['num2', 2],
  ['num3', 3],
]);

const filtered = new Map(
  Array.from(map1).filter(([key, value]) => {
    if (value > 1) {
      return true;
    }

    return false;
  }),
);

// 👇️ {'num2' => 2, 'num3' => 3}
console.log(filtered);

我们使用 Array.from 方法将 Map 转换为键值对数组。

const map1 = new Map([
  ['num1', 1],
  ['num2', 2],
  ['num3', 3],
]);

// 👇️ [['num1', 1], ['num2', 2], ['num3', 3]]
console.log(Array.from(map1));

当我们将 Map 转换为数组时,我们会得到一个二维数组,我们可以在该数组上调用 filter 方法。

每个子数组中的第一个元素是键,第二个元素是对应的值。

我们使用解构赋值来解构我们传递给过滤器方法的回调函数中的键和值。

const [key, value] = ['num1', 1];
console.log(key); // 👉️ num1
console.log(value); // 👉️ 1

在回调函数中,我们检查一个条件,如果条件满足则返回 true,否则返回 false

filter 方法返回一个仅包含元素的新数组,回调函数为其返回一个真值。

最后一步是使用 Map() 构造函数将数组转换回 Map。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

Pandas map()

发布时间:2024/04/24 浏览次数:1652 分类:Python

本教程解释了我们如何使用 Series.map()方法将 Pandas Series 的值替换为另一个值。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便