Javascript Map()

Map – object that stores key:value pairs (can be objects, primitive values, or combo of the two)

Creates an empty Map
const employee = new Map();

Adds key:value pair
.set();

if the key already exists, it will overwrite the existing key:value pair
employee.set('James.parkes@udacity.com', {
firstName: 'James',
lastName: 'Parkes',
role: 'Content Developer'
});

Deletes a key:value pair. Returns true if successful, false it no
.delete();
employee.delete('james.parkes@udacity.com');

Removes all key:value pairs
.clear();

Passing a key to check if a key:value pair is present
.has();

Passing a key to retrieve values
.get();

.keys() and .values() can be used to create an iterable object which can be looped through using next().
let iteratorObjForKeys = members.keys();
creates iterator object and stores the keys in a variable

iteratorObjForKeys.next();
Uses .next() to loop through the keys
Object {value: 'Evelyn', done: false}
What is returned. “done” will return false until end of keys.

Can use .values() to do the same thing, just return values instead.
let iteratorObjForValues = memebers.values();
iteratorObjForValues.next();

Can also loop through Map using a for..of loop
for (const memeber of memebers) {
console.log(member);
}

returns:
['Evelyn', 75.68]
['Liam', 20.16]

With a For..of loop, you get back an array with the first value being the key and the second being the value.

To print the key and value, you’ll need to use array destructuring
for (const member or members){
const [x, y] = memeber;
console.log(x, y);
}

You can also loop through a Map using .forEach()
members.forEach((value, key)) => console.log(key, value);

WeakMaps can only contain objects as keys, do not have a .clear() method and cannot be looped over.
let book1 = { title: 'Pride and Prejudice', author: 'Jane Austen'};
let book2 = { title: 'The Catcher in the Rue', author: 'J.D. Salinger'};
let book3 = { title: 'Gullivers Travels', author: 'Jonathan Swift'};
const library = new WeakMap();
library.set(book1, true);
library.set(book2, false);
library.set(book3, true);
Console.log(library);

To delete an object from a WeakSet, you have to set the object to null. Then JS’s garbage collectors frees up the memory that object used.
book1 = null;
console.log(library);

Advertisements

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.