Maps
A Map is a collection of key/value pairs.
A Map is like a List, but instead of having a numbered index (1, 2, 3), each item corresponds with (or “maps to”) a String key.
Maps are surrounded by curly braces { }
and each key/value pair is joined by a colon :
.
// An empty Map $user = {} // A one-line Map $user = { name: 'Tashi', age: 33 } // A multi-line Map (no commas) $user = { name: 'Tashi' job: 'Technologist' location: 'Tunisia' age: 33 }
TipThink of a List as a collection of many things, while a Map usually holds the properties of a single thing. (It’s very common to have a List of Maps, such as a set of rows from a database query.)
JargonIn other languages, Maps are called many different things: associative arrays, dictionaries, hash maps, hashes, or records. They all basically mean the same thing: a set of key/value pairs.
Accessing Map Fields
Use dot (.
) notation to set and get fields that are defined in the Map.
$user = { name: 'Tashi' age: 33 } $user.name //= 'Tashi' $user.email //= ✕ ERROR - 'email' is not defined
Dynamic Map Values
Often, Maps are used to create an index with dynamic key/value pairs.
Use []
notation to safely set and get dynamic values.
$numBooks = {} $numBooks['Anne Tyler'] = 23 $numBooks['Henry Thoreau'] = 17 $favoriteAuthor = 'Anne Tyler' $numBooks[$favoriteAuthor] //= 23 $numBooks['Nelson Nobody'] //= false (missing value)
Keyword Maps
If you omit a value of a Map property, it will automatically take the value of the key string itself.
$map = { xx, yy, zz } // is the same as... $map = { xx: 'xx' yy: 'yy' zz: 'zz' }
You can use this to emulate an Enumerated Type (aka “Enum”) in other languages.
$alertLevel = { Red, Yellow, Green } if $alert == $alertLevel.Red { print('- Wooop! Wooop! -') }
Map Methods
Here are some common Map methods.
$calories = { taco: 400 taters: 300 tortellini: 500 } $calories.keys() //= ['taco', 'taters', 'tortellini'] $calories.hasKey('taters') //= true
See the Map class for all other methods.