Creating a Javascript Dictionary
If you come from a Python background you're probably used to creating dictionaries and you're wondering how you would create a Javascript dictionary.
The first thing to note is a Javascript dictionary is usually called a Javascript object.
Creating an object in Javascript has the same syntax as creating a dictionary in Python.
const fruitsInventory = {
apples: 56,
oranges: 34,
pears: 983,
bananas: 13,
}
console.log(typeof fruitsInventory) // "object"
There aren't many commonly used built in methods here.
Accessing Properties on a Javascript Dictionary
const fruitsInventory = {
apples: 56,
oranges: 34,
pears: 983,
bananas: 13,
}
console.log(fruitsInventory.apples) // 56
Accessing Properties on a Nested Javascript Dictionary
const inventory = {
fruits: {
apples: 56,
oranges: 34,
pears: 983,
bananas: 13,
},
vegetables: {
cucumbers: 67,
tomatoes: 52,
potatoes: 12
},
meats: {
poultry: {
chicken: 124,
turkey: 356
},
redMeat: {
beef: 300,
}
}
}
console.log(inventory.fruits.oranges) // 34
// As of ES2020 you can use optional chaining to access a property which might not exist and it won't throw an error.
console.log(inventory.fruits.cannedGoods?.beans)
You can call methods on Object
and pass in your object.
const fruitsInventory = {
apples: 56,
oranges: 34,
pears: 983,
bananas: 13,
}
console.log(Object.keys(fruitsInventory)) // ["apples", "oranges", "pears", "bananas"]
console.log(Object.values(fruitsInventory)) // [56, 34, 983, 13]
You'll also find that what you call a list in Python is usually called an array in Javascript.
I hope this was helpful.
tagged
share
Join the mailing list to get new articles straight to your inbox.
No spam, sales or ads. Unsubscribe any time.