Follow this Blog!

Aug 15, 2016

f Comment

[SOLVED] Creating A Map Of Maps In Javascript in SECONDS!

Amazon If you use Javascript, you may be wondering how to create a Javascript map whose value is another map. Although Javascript does not support map inherently, we can use Object to simulate a map. Here's how you do it.

A map, in the algorithm context, contains mappings between a key and a value.

First create a Javascript Object.

var dateMap={};

or

var dateMap = new Object();

Personally I like the former for its simplicity in syntax. You cannot create an Array because an Array uses numbered indexes. As you can tell from the name dateMap, this Object maps a date key to a set of values represented as a map.

Next you fill this map, or Object, with string keys and their associated maps

In my example, the key of the map is a date string, and its value is another map 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:

dateMap['2016-9-1']

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:

dateMap['2016-9-1'].pricePerAdult

or

dateMap['2016-9-1']['pricePerAdult']

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:

dateMap['2016-9-1']['price-of-meal']=1000

You can get 1000 by running the following:

dateMap['2016-9-1']['price-of-meal']

But NOT:

dateMap['2016-9-1'].price-of-meal

because of the special character hyphen in this context.

In JavaScript, arrays use numbered indexes. In JavaScript, objects use named or string indexes.

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
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael