If you’re working with JavaScript and you have to store array of strings or array of objects or any data in a temporary variable to access it somewhere on page then Map is a great way to achieve it. Map provides a great way to get / set data in JavaScript. It holds the key-value pair data and remembers the original insertion order of keys.
I will walk you through how to work with Map in JavaScript.
Initialize a Map type global variable
First of all you have to initialize a global Map
type empty variable. Below code does it for you.
let dataHolder = new Map();
Set your data
As we have already declared a global Map
type variable, now its time to set the data into the variable. Use below function to achieve it.
function _setDataInHolder(key, data) { let existing = dataHolder.get(key); let arrayToSave = [data]; if (existing) { arrayToSave = existing.concat(data); } dataHolder.set(key, arrayToSave); }
The above function expects for two parameters:
- key – the key name in
Map
. Key always should be a string. - data – the data to store. This could be any type of data either string / array / number etc.
In above function, we first check if there is any existing data inside the global variable. If yes, get that and concat our new value in that and then store back in. If not, just put our new value in that and store back.
Get your data
Now we have set our data. Time to get that data and see what happens.
Getting data from a Map
variable is not that hard. You just have to pass the key name in the get
function of Map
and that’s all. It will give you the data whatever will be there. Below code is for your reference.
let data = dataHolder.get(dataKeyName); console.log(data);
where dataKeyName
is the key name you used while storing data.
The complete code is uploaded here on jsFiddle. Just take a look into it and write me back if you stuck somewhere while implementing it.
So that is all for this post. Let’s leave it to you and hope you write me up for any query you face out there.
Have fun. Thank you!