Sub topic 3
Looping over Values with Object.values
This chapter assumes you know arrow functions, for...of, and the array methods reduce, some, and every. It also assumes you have read the previous chapter on Object.keys, because Object.values follows the same rules about which properties it includes.
The working model
Object.values(obj) returns a new array holding the values of the object's own enumerable string-keyed properties. The values come back in the same order that Object.keys would return the keys. You can think of it as Object.keys(obj).map(k => obj[k]) done in one call.
Use it when the property names don't matter for the task. Typical cases are totals, averages, maximums, and checks such as "is any value zero?"
Looping with for...of
The result is an ordinary array, so for...of works on it directly:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const score of Object.values(scores)) {
console.log(score);
}
// 90
// 72
// 85Aggregating values
Aggregations are where Object.values is most useful. With reduce you can sum the values without ever touching a key:
const scores = { alice: 90, bob: 72, carol: 85 };
const total = Object.values(scores).reduce((sum, s) => sum + s, 0);
const average = total / Object.values(scores).length;
console.log(total); // 247
console.log(average); // 82.33333333333333Other array tools work the same way:
const inventory = { apples: 12, pears: 0, plums: 7 };
const counts = Object.values(inventory);
console.log(Math.max(...counts)); // 12
console.log(counts.some(n => n === 0)); // true
console.log(counts.every(n => n >= 0)); // true
console.log(counts.includes(7)); // trueValues are the same values, not copies
Object.values does not clone anything. If a value is an object, the array holds a reference to that same object, so changing it inside the loop changes the original:
const users = {
u1: { name: 'Ada', active: false },
u2: { name: 'Lin', active: false }
};
for (const user of Object.values(users)) {
user.active = true;
}
console.log(users.u1.active); // truePrimitive values behave differently. Reassigning the loop variable only changes the local copy:
const counts = { x: 1, y: 2 };
for (let n of Object.values(counts)) {
n += 10;
}
console.log(counts); // { x: 1, y: 2 }To change primitive values in the original object you need the key, so use Object.keys or Object.entries for that.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Calling `reduce` with no initial value on an empty object | `TypeError: Reduce of empty array with no initial value` | Always pass an initial value, such as `0` |
| `Math.max(...Object.values({}))` | Returns `-Infinity` | Check `length` first |
| Needing the key partway through the loop | You have no way to recover it from a value | Switch to `Object.entries` |
| Passing a `Map` | Returns `[]`, because Map entries are not object properties | Use `map.values()` |
| Expecting duplicate values to collapse | Duplicates are kept | Wrap the array in a `Set` if you want unique values |
The empty-object cases deserve a closer look, because they often come from data loaded at runtime:
const empty = {};
console.log(Object.values(empty).reduce((a, b) => a + b, 0)); // 0
try {
Object.values(empty).reduce((a, b) => a + b);
} catch (err) {
console.log(err instanceof TypeError); // true
}Exercise
Given const temps = { mon: 18, tue: 22, wed: 15, thu: 22 };, write one expression that gives the average temperature, and another that gives the number of distinct temperatures.
Show answer
Average: Object.values(temps).reduce((sum, t) => sum + t, 0) / Object.values(temps).length gives 19.25. Distinct count: new Set(Object.values(temps)).size gives 3.
Exercise
A loop runs for (const item of Object.values(cart)) { item.qty = 0; }, and each value in cart is an object like { qty: 2 }. Does cart change? What if each value were a plain number and the loop ran item = 0 with let item?
Show answer
In the first case cart changes, because each array element refers to the same object stored in cart. In the second case cart does not change, because reassigning item only replaces the local copy of a primitive.