JavaScript 中如何将Map键转换为数组

JavaScript 中将 Map 的键转换为数组:

  1. 调用 Map 上的 keys() 方法以获取包含 Map 中所有键的迭代器对象。
  2. 调用 Array.from() 方法,将迭代器作为参数传递给它。 Array.from 方法从可迭代对象创建一个新数组。
const map = new Map();

map.set('name', 'John');
map.set('age', 30);

const keys = Array.from(map.keys());

console.log(keys); // ?️ ['name', 'age']
console.log(keys.length); // ?️ 2

我们使用 Map.keys 方法获取包含 Map 键的迭代器对象。

我们将迭代器作为唯一参数传递给 Array.from 方法。

Array.from 方法将可迭代对象转换为数组并返回新的数组实例。

这是使用 TypeScript 时推荐的方法,因为编译器在将扩展运算符 (...) 与迭代器一起使用时经常会报错。

另一种方法是使用扩展运算符 …。


使用扩展运算符将映射键转换为数组

将 Map 对象的键转换为数组:

  1. 调用 Map 的 keys() 方法,得到一个包含 Map 的键的迭代器对象。
  2. 使用展开运算符 … 将迭代器中的值解包到一个新数组中。
const map = new Map();

map.set('name', 'John');
map.set('age', 30);

const keys = [...map.keys()];

console.log(keys); // ?️ ['name', 'age']
console.log(keys.length); // ?️ 2

我们使用扩展运算符将 Map 的所有键包含到一个新数组中。

这是将 Map 的键转换为数组时最常用的方法。

我们也可以使用多个map执行此操作。

const map1 = new Map();
map1.set('name', 'John');
map1.set('age', 30);

const map2 = new Map();
map2.set('country', 'Chile');

const keys = [...map1.keys(), ...map2.keys()];

console.log(keys); // ?️ ['name', 'age', 'country']
console.log(keys.length); // ?️ 3