javascript · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
lists an object's keys, ready for a loop.
Object.keys(pet) hands back an array of the object's keys, in the order they were written: ["name", "age", "toy"]. Loop over it with for...of and you visit every key, even ones you did not know were there.
Inside the loop, pet[key] looks up each value with bracket notation. Together they turn any object into a list on the page, one item per key.
<h2>Pet profile</h2>
<ul id="profile"></ul> const pet = { name: "Rex", age: 3, toy: "squeaky ball" };
const profile = document.querySelector("#profile");
for (const key of Object.keys(pet)) {
const item = document.createElement("li");
item.textContent = `${key}: ${pet[key]}`;
profile.append(item);
} Press run it to bring the page to life.
console
nothing logged yet
Object.keys belongs to JavaScript itself, which is why it starts with a capital O.
guess first
How many lines does the recipe card get?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<h2>Pancakes</h2>
<ul id="card"></ul> const recipe = { flour: "100g", eggs: 2, milk: "300ml" };
recipe.sugar = "1 spoon";
const card = document.querySelector("#card");
for (const key of Object.keys(recipe)) {
const line = document.createElement("li");
line.textContent = `${recipe[key]} ${key}`;
card.append(line);
}
your turn
Your turn. Print your own player card.
Fill in a name, a team and a number of goals. Then type the function that lists an object's keys, after Object.. Press run to print the card.
the page your code works on
<h2>Player card</h2>
<ul id="card"></ul>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the card has three linesnot checked yet
- the first line shows the namenot checked yet
- the last line shows the goalsnot checked yet
fix it
The weather report says undefined three times. Fix it!
the page your code works on
<h2>Weather today</h2>
<ul id="weather"></ul>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the first line says sky: sunnynot checked yet
- the last line shows the highnot checked yet
- Every value shows
undefined. Is the code looking up the right key? today.keylooks for a key really called key. The key you want is held in the variablekey.- Change today.key to today[key] on line 5, then press run.
nailed it
you can walk through any object. :D
Object.keys(obj)gives an array of the object's keys.- Loop over it and read each value with
obj[key]. - Keys come out in the order they were added.
new words in your collection
- Object.keys
This lesson isn’t saved. A free account remembers every lesson you finish.