Search code examples
javascriptarraysobjectiterationmaps

Map is not working on Object.keys - JavaScript


I have a simple code where I have a map in JS. I'm iterating over the map keys using Object.keys and then using a map over it to return a new Map. But it is not working and console shows no output.

Here is my code

let map1 = new Map();

let newMap = new Map();
map1.set('111020022AS', true);
map1.set('23t2t363114',false);
map1.set('110AI1123333', true);
map1.set('0000111222',false);

console.log('map is', map1);

console.log('Keys are', Object.keys(map1));

newMap = Object.keys(map1).map(key =>(

    {
        label: key, 
        value: map1[key]
    }

    
))
console.log('new map is', newMap);

this is console output

map is Map(4) {'111020022AS' => true, '23t2t363114' => false, '110AI1123333' => true, '0000111222' => false}[[Entries]]0: {"111020022AS" => true}1: {"23t2t363114" => false}2: {"110AI1123333" => true}3: {"0000111222" => false}size: 4[[Prototype]]:

 
Keys are []   length: 0[[Prototype]]: Array(0)
new map is []

I can't understand where I am going wrong. I just want to make a new Custom Map after iteration using the map function.


Solution

  • let map1 = new Map();
    
    let newMap = new Map();
    map1.set('111020022AS', true);
    map1.set('23t2t363114', false);
    map1.set('110AI1123333', true);
    map1.set('0000111222', false);
    
    console.log('map is', map1);
    
    console.log('Keys are', Object.keys(map1));
    
    newMap = [...map1.entries()].map(([label, value]) => (
      {
        label,
        value
      }
    ))
    console.log('new map is', newMap);