Objects: Grouping Related Data
Model real things with objects, read and update properties with dot and bracket notation, add methods, loop over keys and work with JSON.
Welcome back!
Step 1 of 13Learn
Describing a thing, not a list
An array is great for a list of similar things. But how do you describe one thing with several different properties, like a user with a name, an email, an age and a membership status? You use an object: a collection of key-value pairs.
const user = {
name: "Jordan",
email: "jordan@example.com",
age: 31,
isMember: true,
};Each key (also called a property name) maps to a value, which can be any type, including arrays, other objects and functions.
Reading properties:
- Dot notation:
user.name→ "Jordan" - Bracket notation:
user["email"]→ "jordan@example.com"
Dot notation is shorter and used most of the time. Brackets are needed when the key is stored in a variable (user[field]) or contains spaces or dashes (obj["first-name"]).
Changing and adding works the same way: user.age = 32; updates a property; user.city = "Denver"; adds a new one; delete user.city; removes it. As with arrays, const does not stop you from changing an object's properties.
Reading a property that does not exist gives undefined, not an error. But reading a property of undefined throws a TypeError: if user.address is undefined, user.address.street crashes. The optional chaining operator user.address?.street returns undefined instead of crashing.
Step 2 of 13Diagram
An object is a set of labeled values
Tap a shape with to see more.
- user
- name: "Jordan"
Key
name, a string value. Read it with user.name.- email: "jordan@example.com"
Read with user.email or user["email"].
- age: 31
A number value.
- isMember: true
A boolean value; the is- prefix makes conditions read well.
Step 3 of 13Practice · Fill in the blanks
Fill in the blanks
Given const car = { make: "Toyota", year: 2019 }; and const key = "make";, the expression car[key] gives , while car.key gives .
Step 4 of 13Learn
Methods, nesting and arrays of objects
A function stored in an object is a method. Inside it, the keyword this refers to the object the method was called on:
const account = {
owner: "Priya",
balance: 500,
deposit(amount) {
this.balance += amount;
return this.balance;
},
};
account.deposit(150); // 650You've been using methods all along: console.log, "text".toUpperCase() and array.push() are all methods of built-in objects.
Objects can be nested to model complex data:
const order = {
id: 1042,
customer: { name: "Sam", city: "Austin" },
items: [
{ product: "Mug", price: 12 },
{ product: "Tea", price: 8 },
],
};
order.customer.city // "Austin"
order.items[1].product // "Tea"Arrays of objects are the most common data shape in real applications: a list of products, users, messages or search results. They combine perfectly with the array methods from the previous lesson: order.items.reduce((sum, item) => sum + item.price, 0) gives 20.
To read a path like order.items[1].product, go left to right: the object, its items array, the item at index 1, its product property.
Step 5 of 13Practice · Diagram
The order object as a tree
Each dot or bracket in an expression moves one level down this tree.
Tap the value you reach with order.customer.city.
Tap the shape that answers the question, then press Check.
- order
- id: 1042
- customer { }
- items [ ]
- name: "Sam"
- city: "Austin"
- [0] Mug, 12
- [1] Tea
Step 6 of 13Practice · Choose one
Using the order object above, which expression returns 12?
Step 7 of 13Learn
Looping over objects and destructuring
To process every property of an object, use these built-in helpers:
const stock = { apples: 12, pears: 0, plums: 7 };
Object.keys(stock) // ["apples", "pears", "plums"]
Object.values(stock) // [12, 0, 7]
Object.entries(stock) // [["apples", 12], ["pears", 0], ["plums", 7]]
for (const [fruit, count] of Object.entries(stock)) {
console.log(`${fruit}: ${count}`);
}Because these return arrays, you can chain array methods: Object.values(stock).reduce((a, b) => a + b, 0) gives 19.
Destructuring pulls properties into variables in one line:
const { name, age } = user; // same as name = user.name, age = user.age
const [first, second] = ["gold", "silver", "bronze"];It is especially handy in function parameters: function greet({ name }) { return "Hi " + name; }.
The spread syntax ... copies properties or items: const updated = { ...user, age: 32 }; makes a new object with all of user's properties and a new age, leaving the original unchanged. [...list, newItem] does the same for arrays. Creating updated copies instead of changing the original is a habit that prevents many bugs in larger applications.
Step 8 of 13Note
Step 9 of 13Practice · Code challenge
Write a function countItems(stock) that takes an object whose values are quantities, such as { apples: 12, pears: 0, plums: 7 }, and returns the total quantity.
countItems({ apples: 12, pears: 0, plums: 7 })countItems({})countItems({ pens: 3 })
Step 10 of 13Note
Step 11 of 13Practice · Sort into groups
Is each a valid way to read the email property of user?
Tap an item, then tap its group (or drag it there).
Step 12 of 13Tap to reveal
Arrays or objects? Choosing a shape for your data
Use an array for a list
When you have many items of the same kind and their order matters, such as songs, tasks or messages, use an array. You loop over it, sort it and count it with length.
Use an object for one thing with named parts
When you describe one item with different properties, such as a user with a name, email and age, use an object. You read each part by name, which is clearer than remembering that position 2 means age.
Use an object as a lookup table
When you need to find values by a key quickly, such as prices by product code or translations by word, an object (or a Map) lets you write prices["A17"] instead of searching through an array every time.
Combine them
Real data is usually an array of objects (a list of users) or an object containing arrays (an order with a list of items). Designing this shape well before writing code makes everything that follows simpler.
Step 13 of 13Practice · True or false
const p = { x: 1 }; const q = p; q.x = 5; leaves p.x equal to 1.
Lesson complete!