Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 an mapper containing key/value pair on each iteration:

// ["a_1", "b_2", "c_3"]
map.map((key, value) => key + "_" + value);
like image 385
Denis Kulagin Avatar asked Feb 12 '19 14:02

Denis Kulagin


People also ask

How do you pass a key-value pair on a map?

of("key1", "a", "key2", "b", "key3", "c"); Stream the entry set of map2. Use that entry's key as the key to the result map. use that entry's value as the key to retrieve the value of map1.

How do you use map key-value?

To get its properties as key/value pairs, you can use Object. entries , which you can then apply map to: map = Object. entries(map).

Can a map key have multiple values JavaScript?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

How can I get a value in a JavaScript map by its key?

To get value for a specific key in Map in JavaScript, call get() method on this Map and pass the specific key as argument. get() method returns the corresponding value for given key, if present. If the specified key is not present, then get() returns undefined.


1 Answers

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}`)
like image 52
adiga Avatar answered Oct 13 '22 01:10

adiga