Declaring a Populated HashMap in JavaScript

I was looking for a way to define a pre-populated HashMap today in JavaScript for a custom Chrome Extension I’m writing.

Personally I’ve never liked the syntax of “define the array” and “add items to it one-at-a-time”

Took me a bit to find some examples but in the process I found some great documentation from developers across the web – below are their examples – please go check their content out!

Anyways, here is the final solution that I came up with via StackOverflow.

var inlineHashmap = {
  'cat' : 'asdf',
  'dog' : 'jkl;',
}

inlineHashmap['cat']
> "asdf"

inlineHashmap['dog']
> "jkl;"

JavaScript’s object literal syntax, which is typically used to instantiate objects (seriously, no one uses new Object or new Array), is as follows:

Christoph
https://stackoverflow.com/a/14711978/2520289
var obj = {
    'key': 'value',
    'another key': 'another value',
     anUnquotedKey: 'more value!'
};
For arrays it's:

var arr = [
    'value',
    'another value',
    'even more values'
];

If you need objects within objects, that's fine too:

var obj = {
    'subObject': {
        'key': 'value'
    },
    'another object': {
         'some key': 'some value',
         'another key': 'another value',
         'an array': [ 'this', 'is', 'ok', 'as', 'well' ]
    }
}
This convenient method of being able to instantiate static data is what led to the JSON data format.

JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:

{"foo":"bar", "keyWithIntegerValue":123}

Some time ago, I needed to use a JavaScript hashmap. A hashmap is useful for many reasons, but the main reason I needed one was to be able to find and modify an object, indexed by a unique string, without having to loop through an array of those objects every time.

In order words, I needed to search through my object collection using a unique key value. Key-Value collections are similar to dictionaries in Python, or hashmaps / hashtables in Java.

As far as I can tell, the standard JavaScript language does have a rather simple hashmap implementation, but the “keys” can only be string values. There are some good folks out there who have implemented more complex JS hashmaps. But the ol’ standby is good enough for me, so I’m using it here.

As a Titanium developer, I typically use “Ti.API.log” to print to the console. But since this topic applies to JavaScript in general, I will be using “console.log” for the print statements. For those Titanium developers out there, both function calls should work for you. 🙂

Vui Nguyen aka SunfishGurl
https://sunfishempire.wordpress.com/2014/08/19/5-ways-to-use-a-javascript-hashmap/
So here goes, 5 ways you can use a JavaScript hashmap:

5 – Create hashmap and add keys
// Create the hashmap
var animal = {};
// Add keys to the hashmap
animal[‘cat’] = { sound: ‘meow’, age:8 };
animal[‘dog’] = { sound: ‘bark’, age:10 };
animal[‘bird’] = { sound: ‘tweet’, age:2 };
animal[‘cow’] = { sound: ‘moo’, age:5 };

4 – Print all objects in the hashmap
for (var x in animal)
{
    console.log(‘Key:\n—- ‘ + x + ‘\n’);
    console.log(‘Values: ‘);
    var value = animal[x];
    for (var y in value)
    {
        console.log(‘—- ‘ + y + ‘:’ + value[y]);
    }
    console.log(‘\n’);
}

Here’s a sample of the output:
> Key:
> —- cat
> Values:
> —- sound:meow
> —- age:8
>
> Key:
> —- dog
> Values:
> —- sound:bark
> —- age:10
>
> Key:
> —- bird
> Values:
> —- sound:tweet
> —- age:2
>
> Key:
> —- cow
> Values:
> sound:moo
> —- age:5

3 – Check for the existence of a key, and modify the key
Without a hashmap, you would have to do this:
for (i = 0; i < numObjects; i++)
{
    if (animal[i].type == ‘cat’)
    {
        animal[i].sound = ‘hiss’;
    }
}

But with a hashmap, you can just do this:
// check for the existence of ‘cat’ key
if (‘cat’ in animal)
{
     // modify cat key here
    animal[cat].sound = ‘hiss’;
}
// Sweet, huh?

2 – Delete a key
// check to see if key already exists
if (‘cat’ in animal)
{
     // then, delete it
    delete animal[‘cat’];
}

1 – Count the number of keys
With JS hashmaps, you can’t just do this — animal.length — to get the number of keys, or objects in your hashmap. Instead, you’ll need a few more lines of code:

var count = 0;
for (x in animal)
{ count++; }
console.log(‘The number of animals are: ‘ + count + ‘\n’);

Here’s a sample of the output:
> The number of animals are: 4

There you have it, 5 ways to use a JavaScript hashmap. If you have examples of other uses, or if you’ve implemented a JS hashmap yourself that you’d like to share, please feel free to drop the link to your code in the comments below.

And finally, I referenced the following articles to help me with writing this one. Many thanks to the authors! :
http://stackoverflow.com/a/8877719
http://www.mojavelinux.com/articles/javascript_hashes.html
http://www.codingepiphany.com/2013/02/26/counting-associative-array-length-in-javascript/

Thanks, and hope you find this article useful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s