Maps are objects but what is the type of value inside the object

I was recently learning maps and when I tried the code below:

let a = [
    [false, 1],
    ['1', 'str1'],
    [1, 'num1'],
    [true, 'bool1']
]

let map1 = new Map(a);

console.log(map1);

It output me:

Map { false => 1, '1' => 'str1', 1 => 'num1', true => 'bool1' }

So I can see it's an object(due to {}) but what is the type of value inside the curly braces. I cannot understand. So please anyone tell what is the type of the value and can I get the value from the key without using get method.
By the way I am using node js to execute the code.

1 answer

  • answered 2021-05-14 23:10 CertainPerformance

    The output you're seeing is a formatting convention for how to display Maps when examined in the console. The map doesn't actually hold the keys and values as own-properties - rather, the keys and values are held internally, available only to the internals of the Map implementation, which exposes them through the various Map methods like .values(), .keys(), .get(), and so on.

    can I get the value from the key without using get method.

    I suppose you could use .entries() to turn the Map into an array, then look through the array for the matching key:

    let a = [
        [false, 1],
        ['1', 'str1'],
        [1, 'num1'],
        [true, 'bool1']
    ]
    
    let map1 = new Map(a);
    
    const entries = [...map1.entries()];
    
    const entry = entries.find(e => e[0] === 1);
    console.log(entry[1]);

    But that's really weird.

    There's no way to get the saved values on a Map without using one of the Map's built-in methods - but that's OK, since you should always be using the built-in methods to process a Map. Go ahead and use .get.