Search code examples
javascriptdictionarydata-structures

How to map key/value pairs of a "map" in JavaScript?


How to map key/value pairs of a "map" in JavaScript:

var map = {"a": 1, "b": 2, "c": 3};

alert(JSON.stringify(map));

I need to get a mapper containing key/value pair on each iteration:

// ["a_1", "b_2", "c_3"]
map.map((key, value) => key + "_" + value);

Solution

  • This is not a Map object. It's just a regular object. So, use Object.entries and then use map on the key value pair:

    const map = {"a": 1, "b": 2, "c": 3};
    const mapped = Object.entries(map).map(([k,v]) => `${k}_${v}`);
    console.log(mapped);

    Object.entries returns:

    [["a",1],["b",2],["c",3]]
    

    Then loop through each of those inner arrays and create the string using template literals


    If you have a Map object, use Array.from(map) to get the entries of the map and use the second parameter of Array.from to go over each entry and create the desired string

    Array.from(map, ([k,v]) => `${k}_${v}`)