Map to Variety in JavaScript

In this short article, we will transform a Map challenge a Selection in JavaScript A Map is a collection of key-value sets related to each other. The following are the methods to Map to Variety conversion:

Approaches to transform Map to Variety

Utilizing the Spread operator( …) and map() technique, we can take each entry and transform it into a selection of key-value sets.

Syntax:

 let Variety = [...value];
// Arrow function
Array.map(( e) => > e);
Array.map(( e, i) => > {i, e} );

Example: This example shows the execution of the Spread Operator (…) Technique and Variety map() Technique.

Javascript

const mapObj = brand-new Map();

mapObj.set( 1, ' abc');

mapObj.set( 2, ' xyz');

mapObj.set( 3, ' pqr');

console.log( mapObj);

let arr =[...mapObj] map(( e) => > e)

console.log( arr);

Output
 Map( 3) {1 => > 'abc', 2 => > 'xyz', 3 => > 'pqr'} 

. [ [ 1, 'abc' ], [ 2, 'xyz' ],[ 3, 'pqr' ]] 
. 

Technique 2: Utilizing Array.from() Technique

The Array.from() Technique returns a brand-new circumstances of a selection from the item offered in the arguments.

Syntax:

 Array.from( item, mapFunction, thisValue);

.

. 

Example: In this example, we will pass a map item and a function into Array.from() Technique to transform it into a selection.

Javascript

const mapObj = brand-new Map();

mapObj.set( 1, ' abc');

mapObj.set( 2, ' xyz');

mapObj.set( 3, ' pqr');

console.log( mapObj);

let arr = Array.from( mapObj);

console.log( arr);

Output
 Map( 3) {1 => > 'abc', 2 => > 'xyz', 3 => > 'pqr'} 

. [ [ 1, 'abc' ], [ 2, 'xyz' ],[ 3, 'pqr' ]] 
. 

JavaScript map.forEach() technique is utilized to repeat the map item and perform the callback function offered in the arguments.

Syntax:

 mymap.forEach();

. 

Example: This example shows the execution of the map.forEach() Technique.

Javascript

const mapObj = brand-new Map();

mapObj.set( 1, ' abc');

mapObj.set( 2, ' xyz');

mapObj.set( 3, ' pqr');

console.log( mapObj);

const arr = [];

mapObj.forEach(

( worth, secret) => > arr.push(

{essential, worth} ));

console.log( arr);

Output
 Map( 3) {1 => > 'abc', 2 => > 'xyz', 3 => > 'pqr'} 

.
[
  { key: 1, value: 'abc' },
  { key: 2, value: 'xyz' },
  { key: 3, value: 'pqr' }
] 
.

There are numerous integrated JavaScript approaches that can be utilized to change information from one information type to another. Above pointed out are a few of those that can be quickly carried out to transform the Map challenge a selection.

Last Upgraded:
29 Jun, 2023

Like Post

Conserve Post

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: