Course outline · 0% complete

0/29 lessons0%

Course overview →

Nesting and iterating objects

lesson 5-2 · ~10 min · 15/29

Objects inside objects

Real data nests. A student has grades, grades have subjects:

const student = {
  name: "Ada",
  grades: { math: 95, cs: 99 }
};

console.log(student.grades.math);  // 95

Chain the dots one level at a time. If a middle link might be missing, student.grades?.math answers undefined instead of crashing (the optional chaining operator ?.).

Looping over properties

Objects are not directly for...of iterable. Instead, three helpers turn an object into an array first:

  • Object.keys(obj) → array of key strings
  • Object.values(obj) → array of values
  • Object.entries(obj) → array of [key, value] pairs

With entries you can unpack each pair right in the loop header, like Python's for k, v in d.items():

for (const [subject, grade] of Object.entries(student.grades)) {
  console.log(`${subject}: ${grade}`);
}

The [subject, grade] part is called destructuring: it splits a two-item array into two named variables.

studentname: "Ada"gradesmath: 95cs: 99student.namestudent.grades.math
Nested objects form a tree. Each dot in student.grades.math walks one level down.

Code exercise · javascript

Run it. Chained dots reach into the nest, Object.entries feeds the loop, and Object.keys shows the top-level property names.

Code exercise · javascript

Your turn. Loop over the prices object with Object.entries and print one line per item in the form: coffee costs $3

Code exercise · javascript

Second practice. Total the cart: Object.values gives you just the prices, and a for...of loop (lesson 3-3) adds them into total. Print the result.

Quiz

Which call gives you an array of [key, value] pairs, like Python's dict.items()?