Objects: Grouping Related Data
16 minBeginnerHTML · CSS · JS
In this lesson
- ▸Create objects and read properties with dot and bracket notation
- ▸Work with nested objects and arrays of objects
- ▸Turn an object's data into arrays with
Object.keysandObject.entries
The big idea
An array answers "what is item number 3?". An object answers "what is this thing's price?" — it stores values under names (keys) instead of positions.
A student has a name, an age and a home town. You could keep three separate variables, but they belong together. An object bundles them into one value made of key: value pairs, called properties.
const student = {
name: "Aina",
age: 17,
subjects: ["Maths", "Biology"], // a value can be an array…
address: { // …or another object
city: "Kuching",
state: "Sarawak",
},
};
student.name; // "Aina"
student.address.city; // "Kuching" ← follow the dots inwards
student.subjects[0]; // "Maths"
student.email; // undefined ← no such propertyDot or brackets?
Dot notation — the name is fixed
student.age = 18;
student.school = "SMK Batu Lintang";Brackets — the name is a string or a variable
const field = "age";
student[field]; // 18
student["home town"] = "Kuching";Use dots most of the time. Use brackets when the key is stored in a variable or contains spaces or dashes.
A classic bug
student.field looks for a property literally called "field". If the name is inside a variable, you need student[field].
Arrays of objects
Real data is usually a list of things that each have several properties — products, messages, students. That's an array of objects, and map/filter from the last lesson work beautifully on it.
const menu = [
{ name: "Nasi Lemak", price: 6.5, spicy: true },
{ name: "Roti Canai", price: 2, spicy: false },
];
menu[1].price; // 2
menu.map((dish) => dish.name); // ["Nasi Lemak", "Roti Canai"]
menu.filter((dish) => dish.price < 5); // [{ name: "Roti Canai", … }]Looking inside an object
const scores = { Aina: 82, Ben: 67 };
Object.keys(scores); // ["Aina", "Ben"]
Object.values(scores); // [82, 67]
Object.entries(scores); // [["Aina", 82], ["Ben", 67]]
"Aina" in scores; // true — does this key exist?
// Each entry is a little [key, value] array:
Object.entries(scores).map((pair) => pair[0] + " got " + pair[1]);
// The same, unpacking the pair straight away:
Object.entries(scores).map(([name, score]) => name + " got " + score);Methods: functions inside objects
const cart = {
items: ["teh tarik"],
add(item) {
this.items.push(item); // "this" = the object the method was called on
},
};
cart.add("kuih");
cart.items; // ["teh tarik", "kuih"]You've used methods all along: cart.items.push is the push method of an array, and console.log is the log method of the console object.
Finish the two functions in script.js:
1. describe(person) returns a sentence like "Aina (17) from Kuching", using the person's name, age and the city inside their address.
2. getField(obj, key) returns the value stored under key, or the string "unknown" if the object has no such key. Careful: a value of 0 is still a real value.
Checks
- describe builds the sentence from nested data
- getField reads any key and handles missing ones
Check understanding
What you learned
- ✓Objects store values under names:
{ key: value }. Values can be anything — even arrays and other objects. - ✓Use
obj.keyfor fixed names andobj[variable]when the key is in a variable or has spaces. - ✓Arrays of objects +
map/filteris how most real app data is handled. - ✓
Object.keys,Object.valuesandObject.entriesturn an object into arrays you can work with.
Console output from your code appears here.