Objects: grouping data
Arrays are great for lists of similar things. But what about one thing with lots of details, like a player in a game? That is what objects are for:
const player = {
name: "Ada",
level: 3,
online: true,
};
An object is a bunch of key: value pairs inside curly brackets, separated by commas. The keys (name, level, online) are labels; the values can be anything: strings, numbers, booleans, arrays, even other objects.
You read a value with a dot:
console.log(player.name); // Ada
and you change or add one the same way:
player.level = 4; // update
player.score = 1200; // add a new key
Same trick as arrays: const stops you replacing the whole object, but you can still change what is inside it.
There is a second way to read keys, with square brackets and a string: player["name"]. You need it when the key is stored in a variable:
const key = "level";
console.log(player[key]); // 4
Ask for a key that does not exist and you get undefined, not an error. Handy, but it also means a typo like player.nmae fails silently. Read your keys carefully.
Arrays of objects
Real data is very often a list of objects. A list of players, messages, songs:
const team = [
{ name: "Ada", level: 4 },
{ name: "Sam", level: 2 },
];
console.log(team[1].name); // Sam
This shape is basically what most apps send around the internet all day, so get comfy with it.
Try it yourself
Edit it. Break it. Run it again.const player = {
name: "Ada",
level: 3,
items: ["sword", "map"],
};
console.log(player.name);
console.log(player.items[1]);
player.level = 4;
player.score = 1200;
console.log(player);
const key = "level";
console.log(player[key]);
console.log(player.nmae);
const team = [{ name: "Ada", level: 4 }, { name: "Sam", level: 2 }];
for (const p of team) {
console.log(`${p.name} is level ${p.level}`);
}
Your turn
Type it yourself. That is the whole trick.1Read the profile
Using the pet object, print exactly: Biscuit is a dog aged 4
const pet = { name: "Biscuit", species: "dog", age: 4 };
console.log("pet is a species aged age");
2Level up
Change player so that its level is 5, and add a new key badge with the value "gold". Do it with dot notation, after the object is created.
const player = { name: "Ada", level: 4 };