Index
Coding a Map Using Objects


A map (or dictionary) is an key-value lookup. Like a word dictionary. Given a key we look up a value. A key is associated with a value.

This lab is almost identical to our "Plain Objects Lab". That is because JavaScript plain objects support the same protocol as maps/dictionaries.

NOTE WELL -- Almost all older code will use this style of map/dictionary. However, if we're writing new code we generally prefer using a Map object type over using objects as maps.

Constructing and initializing a map using a simple object

//Initialize map
const obj = { 'width': 1000, 'pickle': 2000,
				'fun': 3000, 'big': 4000};
Getting values from map (object)

let obj;
obj = { 'width': 1000, 'pickle': 2000,
			'fun': 3000, 'big': 4000};

//Now we "get" the value at the key

//Syntax option 1 is "<object>.<key>"
prn(obj.width);
prn(obj.pickle);

//Syntax option 2 is "<object>['key']"
prn(obj['width']);
prn(obj['pickle']);
Setting values into map (object)

let obj;

//Now we "set" key-value pairs into map

//Two styles (similar to "gettingValues")

//Syntax option 1 is "<object>.<key> = <value>"
obj = {};
obj.width = '1000';
obj.height = '5';
prn(obj.width);
prn(obj.height);

//Syntax option 2 is "<object>['key'] = <value>"
obj = {};
obj['cucumber'] = '5000';
obj['clown'] = '3';
prn(obj['cucumber']);
prn(obj['clown']);
Iterating over the map

//Initialize map
const obj = { 'width': 1000, 'pickle': 2000,
				'fun': 3000, 'big': 4000};

//Iterate
for (let key in obj){
	prn(`key is "${key}", value is ${obj[key]}`);
}

More Example Sources


Here are a couple (among many more) online related example sources: