Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Last active November 25, 2020 02:22
Show Gist options
  • Save whal-e3/47edec9b960a868d42fef19f9571949a to your computer and use it in GitHub Desktop.
Save whal-e3/47edec9b960a868d42fef19f9571949a to your computer and use it in GitHub Desktop.
JS maps (key - value pair)
// MAP (key-value pair)
const map = new Map();
const key1 = 'string key',
key2 = {},
key3 = function () {};
map.set(key1, 'value of key1');
map.set(key2, 'value of key2');
map.set(key3, 'value of key3');
console.log(map.get(key1));
console.log(map.size);
// Iterating
for (let [key, value] of map) {
console.log(`${key} = ${value}`);
}
for (let key of map.keys()) {
console.log(key);
}
for (let value of map.values()) {
console.log(value);
}
map.forEach(function (value, key) {
console.log(`${key} = ${value}`);
});
// Convert to Array
const keyValArr = Array.from(map);
const valArr = Array.from(map.values());
const keyArr = Array.from(map.keys());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment