DevPath · Learn to code ESPTEN

Objects

Iterating over objects: keys, values, and entries

Iterating over an object

Picture a cart with the price of each product, and you want to add up the total. For that you need to iterate over the object. The catch: unlike arrays, objects don't have numeric indexes, so there's no [0], [1] to grab onto. The solution is the Object utilities.

Object.keys: the keys

const person = { name: "Ana", age: 30 };
console.log(Object.keys(person)); // ["name", "age"]

Object.values: the values

console.log(Object.values(person)); // ["Ana", 30]

Object.entries: [key, value] pairs

console.log(Object.entries(person));
// [["name", "Ana"], ["age", 30]]

Iterating with for...in

The for...in loop iterates over an object's keys:

for (const key in person) {
  console.log(key, "=>", person[key]);
}

Combining with array methods

Here the circle closes: since Object.keys and Object.values return arrays, you can chain the map, filter, or reduce you already master. That cart from the start, solved in one line:

const prices = { bread: 2, milk: 1, coffee: 5 };
const total = Object.values(prices).reduce((a, b) => a + b, 0); // 8

And with this you wrap up the JavaScript fundamentals block. Pause for a second and look at everything you can do now: variables, conditionals, loops, functions, arrays, and now objects with methods. You're no longer writing "loose snippets": you model real-world data and process it. From here on (ES6, the DOM…) everything builds on these foundations. Well done.

Examples

Compute the average from a grades object

const grades = { math: 8, language: 7, science: 9 };
const keys = Object.keys(grades);
const sum = Object.values(grades).reduce((a, b) => a + b, 0);
console.log(keys);            // ["math", "language", "science"]
console.log("Average:", sum / keys.length); // 8
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Methods and thisView the module →