js - Maps

can write key-value pair with the help of map

const myMap = new Map()

const key1 = 'mystr1' , key2 = {} , key3 = function(){}

// Setting map values
myMap.set(key1,'this is string')
myMap.set(key2,'this is blank object')
myMap.set(key3,'this is an empty function')

// console.log(myMap);

// getting value from the map
let value1 = myMap.get(key1)
let value2 = myMap.get(key2);
let value3 = myMap.get(key3);

// console.log(value1);
// console.log(value2);
// console.log(value3);

// get the size of the map
// console.log(myMap.size);

// you can use for..of  to get keys and value
// for(let [key,value] of myMap){
//     console.log(`key : ${key} , value : ${value}`);
// }

// // get only keys
// for(let key of myMap){
//     console.log(`key is : ${key}`);
// }

// // get only values
// for(let value of myMap){
//     console.log(`value is : ${value}`);
// }

// looping map using foreach loop
// myMap.forEach((value,key) => {
//     console.log(`key : ${key} , value : ${value}`);
    
// });

// converting map to array

let myArray = Array.from(myMap)
console.log("ARRY", myArray);


let myKeyArray = Array.from(myMap.keys());
console.log("ARRY", myKeyArray);

let myValueArray = Array.from(myMap.values());
console.log("ARRY", myValueArray);


0 Comments