Sub topic 3
Looping over Values with Object.values
Sometimes you only care about what an object holds, not what each item is called. Totals, averages, maximums, "is any flag turned off?" checks, and tallies all need the values and never look at the keys. Object.values is the tool for these jobs.
This chapter assumes you know variables, arrow functions, object literals, arrays, for...of, and basic array methods such as map, filter, and reduce. It also builds on the previous two chapters. Those covered which properties count as "own enumerable" and how Object.keys returns them as an array.
What Object.values Returns
Object.values(obj) returns a new array that holds the values of the object's own enumerable string-keyed properties. It covers the same set of properties as Object.keys, and in the same order. The only difference is that you get the values instead of the names.
const stock = { apples: 12, pears: 0, plums: 7 };
console.log(Object.keys(stock)); // ['apples', 'pears', 'plums']
console.log(Object.values(stock)); // [12, 0, 7]Position i in the values array belongs to the key at position i in the keys array, as long as the object does not change between the two calls. So Object.values behaves like this longer expression:
const stock = { apples: 12, pears: 0, plums: 7 };
const viaKeys = Object.keys(stock).map((key) => stock[key]);
const direct = Object.values(stock);
console.log(viaKeys); // [12, 0, 7]
console.log(direct); // [12, 0, 7]When the key name is unused, Object.values is shorter and says what you mean. Someone reading Object.values(stock) can tell right away that the names don't matter in this code.
Looping with for...of
The returned value is an ordinary array, so for...of loops over it directly:
const stock = { apples: 12, pears: 0, plums: 7 };
for (const count of Object.values(stock)) {
console.log(count);
}
// 12
// 0
// 7Name the loop variable after what each value is (count, price, user). Generic names like value make the loop harder to read.
Aggregating Values
The most common use of Object.values is collapsing an object into a single number.
Sums with reduce
const scores = { alice: 90, bob: 72, carol: 85 };
const total = Object.values(scores).reduce((sum, s) => sum + s, 0);
console.log(total); // 247Maximum, minimum, and average
Spreading the array into Math.max or Math.min gives you the extremes. An average needs the sum and the array's length:
const scores = { alice: 90, bob: 72, carol: 85 };
const values = Object.values(scores);
const highest = Math.max(...values);
const lowest = Math.min(...values);
const average = values.reduce((sum, s) => sum + s, 0) / values.length;
console.log(highest); // 90
console.log(lowest); // 72
console.log(average); // 82.33333333333333Store the array in a variable when you use it more than once, as above. Every call to Object.values builds a new array, and calling it three times in a row repeats the work.
Yes-or-no questions about values
some, every, and includes answer questions about the whole collection:
const flags = { darkMode: true, beta: false, analytics: true };
const values = Object.values(flags);
console.log(values.includes(false)); // true
console.log(values.every(Boolean)); // false
console.log(values.some((on) => on)); // true
console.log(values.filter(Boolean).length); // 2includes compares with SameValueZero, which is strict equality except that NaN matches NaN. It finds primitive values without trouble. For object values it only matches the exact same reference, never an object that merely looks the same.
Tallies and unique values
The values of one object can become the keys of another. Counting how often each value appears looks like this:
const votes = { ann: 'yes', ben: 'no', cy: 'yes', dee: 'abstain' };
const tally = {};
for (const vote of Object.values(votes)) {
tally[vote] = (tally[vote] ?? 0) + 1;
}
console.log(tally); // { yes: 2, no: 1, abstain: 1 }
const distinct = [...new Set(Object.values(votes))];
console.log(distinct); // ['yes', 'no', 'abstain']Values Are Copies of Primitives but Shared References to Objects
Beginners often expect that changing a value inside the loop will update the object. Whether it does depends on what kind of value it is.
Object.values copies each property's current value into the new array. When the value is a primitive, such as a number, string, or boolean, reassigning the loop variable only changes your local copy:
const prices = { apple: 1.2, pear: 0.8 };
for (let price of Object.values(prices)) {
price = price * 2; // changes the local variable only
}
console.log(prices); // { apple: 1.2, pear: 0.8 }When the value is an object, the array holds a reference to that same object. Changing one of its properties through the loop variable changes the original:
const users = {
u1: { name: 'Ada', active: false },
u2: { name: 'Linus', active: false },
};
for (const user of Object.values(users)) {
user.active = true; // mutates the shared nested object
}
console.log(users.u1.active, users.u2.active); // true trueGetters Run When Object.values Is Called
Accessor properties defined with get are read like any other property. Object.values calls each enumerable getter once and stores the result:
const temp = {
celsius: 20,
get fahrenheit() {
return (this.celsius * 9) / 5 + 32;
},
};
const snapshot = Object.values(temp);
console.log(snapshot); // [20, 68]
temp.celsius = 30;
console.log(snapshot); // [20, 68] (unchanged)
console.log(Object.values(temp)); // [30, 86]There are two consequences. A getter that is slow or has side effects runs every time you call Object.values. And the array is a snapshot taken at the moment of the call. It does not follow later changes to the object.
The Empty-Object Trap
An empty object produces an empty array. That is fine on its own, but some aggregation patterns fail on empty input:
const empty = {};
const values = Object.values(empty);
console.log(values); // []
// With an initial value, reduce is safe:
console.log(values.reduce((sum, v) => sum + v, 0)); // 0
// Without one, reduce throws on an empty array:
try {
values.reduce((sum, v) => sum + v);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(Math.max(...values)); // -Infinity
console.log(values.reduce((s, v) => s + v, 0) / values.length); // NaN| Expression on an empty object | Result | Fix |
|---|---|---|
| `reduce(fn)` with no initial value | Throws `TypeError` | Always pass an initial value, such as `0` |
| `Math.max(...values)` | `-Infinity` | Check `values.length` first |
| `Math.min(...values)` | `Infinity` | Check `values.length` first |
| `sum / values.length` | `NaN` (0 / 0) | Return `0` or `null` when the length is zero |
| `values.every(fn)` | `true` | Decide whether "all of nothing" should count as true |
The every row is easy to miss. An empty object passes every every test, so "all flags enabled" comes out true when there are no flags at all. When that result would be wrong for your program, check values.length > 0 as well.
When Object.values Is the Wrong Tool
Once you call Object.values, the link between each value and its key is gone. That becomes a problem when the answer to your question is a key. Take "who scored highest?":
const scores = { alice: 90, bob: 72, carol: 85 };
const highest = Math.max(...Object.values(scores));
console.log(highest); // 90, but whose score is it?
// Searching back for the key is clumsy and breaks on ties:
const who = Object.keys(scores).find((name) => scores[name] === highest);
console.log(who); // 'alice'Searching back for the key works here, but it loops over the object twice, and when two keys share the top score it returns only the first one. If you need both the key and the value, Object.entries (the next chapter) keeps them together in pairs.
| Task | Best choice |
|---|---|
| Sum, average, min, max of all values | `Object.values` |
| Check whether any or all values meet a condition | `Object.values` with `some` or `every` |
| Count or deduplicate values | `Object.values` |
| Find which key holds a value | `Object.entries` |
| Update the object's own properties | `Object.keys` or `Object.entries` |
| Print "name: value" lines | `Object.entries` |
What Object.values Skips
Object.values follows the same inclusion rules as Object.keys. It ignores inherited properties, non-enumerable properties, and symbol-keyed properties:
const base = { inherited: 'from prototype' };
const item = Object.create(base);
item.own = 'mine';
item[Symbol('tag')] = 'symbol value';
Object.defineProperty(item, 'hidden', { value: 'secret', enumerable: false });
console.log(Object.values(item)); // ['mine']Later chapters cover why each of these is excluded and how to reach them when you need to.
Exercise
Given const cart = { shirt: 25, socks: 5, hat: 15 }, write one expression that returns the total cost, and explain why it should include a second argument to reduce.
Show answer
Object.values(cart).reduce((sum, price) => sum + price, 0) returns 45. The initial value 0 makes the expression return 0 for an empty cart. Without it, reduce throws a TypeError on an empty array.
Exercise
After running const teams = { red: { wins: 1 }, blue: { wins: 2 } }; for (let t of Object.values(teams)) { t.wins += 1; t = null; } what are teams.red.wins and teams.blue.wins, and is either property now null?
Show answer
teams.red.wins is 2 and teams.blue.wins is 3. Each value is a reference to a nested object, so t.wins += 1 changes the shared object. Setting t = null only reassigns the local loop variable, so teams.red and teams.blue still point to their objects and neither is null.
Exercise
A function allEnabled(flags) returns Object.values(flags).every(Boolean). What does allEnabled({}) return, and how would you change the function so an empty object returns false?
Show answer
It returns true, because every is true for an empty array. Change it to: const values = Object.values(flags); return values.length > 0 && values.every(Boolean);