JavaScript 将Map转换为数组
在本文中,我们将把一个Map对象转换为JavaScript中的数组。Map是一组彼此关联的键值对的集合。以下是将Map转换为数组的方法:
将Map转换为数组的方法
- 使用Spread Operator(…)和Array map()方法
- 使用Array.from()方法
- 使用Map.forEach()方法
方法1:使用Spread Operator (…)和Array map()方法
使用Spread Operator(…)和map()方法,我们可以将每个条目转换为一个键值对数组。
语法:
let Array = [...value];
// Arrow function
Array.map((e) => e);
Array.map((e, i) => {i,e});
例子: 此例子展示了使用Spread Operator(…)方法和Array map()方法的实现方式。
Javascript
const mapObj = new Map();
mapObj.set(1, 'abc');
mapObj.set(2, 'xyz');
mapObj.set(3, 'pqr');
// Return the map
console.log(mapObj);
let arr = [...mapObj].map((e) => e)
// Return the array
console.log(arr);
输出
Map(3) { 1 => 'abc', 2 => 'xyz', 3 => 'pqr' }
[ [ 1, 'abc' ], [ 2, 'xyz' ], [ 3, 'pqr' ] ]
方法2:使用Array.from()方法
Array.from()方法从提供的参数对象返回一个新的数组实例。
语法:
Array.from(object, mapFunction, thisValue);
示例: 在这个示例中,我们将一个地图对象和一个函数传递给Array.from()方法,将其转换为一个数组。
JavaScript
const mapObj = new Map();
mapObj.set(1, 'abc');
mapObj.set(2, 'xyz');
mapObj.set(3, 'pqr');
// Return the map
console.log(mapObj);
// Return the array
let arr = Array.from(mapObj);
console.log(arr);
输出
Map(3) { 1 => 'abc', 2 => 'xyz', 3 => 'pqr' }
[ [ 1, 'abc' ], [ 2, 'xyz' ], [ 3, 'pqr' ] ]
方法3:
使用 Map.forEach() 方法
JavaScript 的 map.forEach() 方法用于迭代 map 对象并执行提供的回调函数。
语法:
mymap.forEach();
示例: 此示例演示了map.forEach()方法的实现。
Javascript
const mapObj = new Map();
mapObj.set(1, 'abc');
mapObj.set(2, 'xyz');
mapObj.set(3, 'pqr');
// Return the map
console.log(mapObj);
const arr = [];
mapObj.forEach(
(value, key) => arr.push(
{ key, value }));
// Return the array
console.log(arr);
输出
Map(3) { 1 => 'abc', 2 => 'xyz', 3 => 'pqr' }
[
{ key: 1, value: 'abc' },
{ key: 2, value: 'xyz' },
{ key: 3, value: 'pqr' }
]
有许多内置的JavaScript方法可以用来将数据从一种数据类型转换为另一种。上述是其中的一些,可以很容易地实现将Map对象转换为数组。