Created
February 5, 2022 16:02
-
-
Save leighhalliday/31430d36b49e7296e7a2ef603e2084ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Instantiate | |
const map = new Map([ | |
[1, "one"], | |
[2, "two"], | |
]); | |
const obj = { | |
1: "one", | |
2: "two", | |
}; | |
console.log({ map, obj }); | |
// Set | |
map.set(3, "three"); | |
obj[3] = "three"; | |
// Get | |
console.log("map get", map.get(3)); | |
console.log("obj get", obj[3]); | |
// Delete | |
map.delete(3); | |
delete obj[3]; | |
// Keys | |
console.log("map keys", map.keys()); | |
console.log("obj keys", Object.keys(obj)); | |
// Has | |
console.log("map has key 1", map.has(2)); | |
console.log("obj has key 1", 2 in obj); | |
console.log("obj has key 1", obj.hasOwnProperty(2)); | |
// Values | |
console.log("map values", map.values()); | |
console.log("obj values", Object.values(obj)); | |
// Entries | |
console.log("map entries", map.entries()); | |
console.log("obj entries", Object.entries(obj)); | |
// Length | |
console.log("map size", map.size); | |
console.log("obj size", Object.keys(obj).length); | |
// Iteration for | |
for (const [key, value] of map) { | |
console.log({ key, value }); | |
} | |
for (const [key, value] of Object.entries(obj)) { | |
console.log({ key, value }); | |
} | |
// Iteration forEach | |
map.forEach((value, key) => console.log({ key, value })); | |
Object.entries(obj).forEach(([key, value]) => console.log({ key, value })); | |
// Swap Keys & Values | |
const swapMap = Array.from(map).reduce( | |
(acc, [key, value]) => acc.set(value, key), | |
new Map() | |
); | |
const swapObj = Object.entries(obj).reduce( | |
(acc, [key, value]) => ({ ...acc, [value]: key }), | |
{} | |
); | |
console.log({ swapMap, swapObj }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment