Aug 15, 2016

f Comment

Create Javascript Map With Array Value

Amazon If you use Javascript, you may be wondering how to create a Javascript map whose value is an Array of keys and values. Although Javascript does not support map, we can use a simple way to simulate a map. Here's how you do it.

First create a Javascript Object.

var dateMap={};


var dateMap = new Object();

Personally I like the former for its simplicity in syntax.

Next you fill this map with keys and their corresponding Array value.

In my example, the key of the map is a date, and its value is an array containing a set of information about this date. Here's the Javascript code:

dateMap['2016-9-1'] = {pricePerAdult:2499, pricePerKid:1499};
dateMap['2016-9-2'] = {pricePerAdult:3499, pricePerKid:2499};

As you can see, on 2016/9/1, the price per adult is $2499, the price per kid is $1499. On 2016/9/1, the price per adult is $3499, the price per kid is $2499.

Next let's look at how to access each element.

Here's the Javascript to access an element in the map dateMap:


What element will this statement return? The answer is an Object that looks like this:

Object {pricePerAdult: 2499, pricePerKid: 1499}

Let's say you want to know the price per adult on 2016/9/1, how do you do it? Either of the following works:




Although I prefer the former for its simplicity and readability, the latter is more correct and less risky. For example, let's say you execute the following Javascript code:


You can get 1000 by running the following:


But NOT:


because of the special character hyphen in this context.

Hope this tutorial on how to simulate a map in Javascript helps you.

Questions? Let me know!

Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael