Turning an object into something you can loop over comes up all the time. You need it to count the items in a response, to list the fields of a form, or to find the highest score in a record. JavaScript gives you three static methods for that job, one loop that needs a little care, and a modern grouping method that replaces a lot of hand-written code.
The previous lesson in this module covered "Object References vs a Real Copy", and the next lesson in this module is about "JSON.parse and JSON.stringify in Real Work".
What do Object.keys, values and entries give me?
Three static methods and three shapes. Object.keys() gives you the names, Object.values() gives you the values, and Object.entries() gives you both as an array of two-element pairs. All three of them return plain arrays, so every array method works on the result.
const scores = { Ada: 12, Linus: 9, Grace: 20 };
console.log(Object.keys(scores)); // [ 'Ada', 'Linus', 'Grace' ]
console.log(Object.values(scores)); // [ 12, 9, 20 ]
console.log(Object.entries(scores)); // [ [ 'Ada', 12 ], [ 'Linus', 9 ], [ 'Grace', 20 ] ]
Three details about that output are worth keeping in your head. The order follows the object's own key order, and for string keys that is the order in which the keys were first added. The keys are always strings, even when you write them as numbers in the literal. And the arrays are new, but a value that is itself an object is still the very same object, because the reference rule from the previous lesson applies here as well.
How do I loop over an object's properties?
for...in walks the enumerable property names of an object. The body has the same shape as the array version, with a name and then the value.
const settings = { theme: 'dark', fontSize: 14 };
for (const key in settings) {
console.log(key, settings[key]);
}
// theme dark
// fontSize 14
There is no entries() helper for objects, but you get the same result by looping over Object.entries(obj) with for...of. That reads better when you want the key and the value as two named variables.
Why does for...in need an Object.hasOwn guard?
Because for...in also walks inherited enumerable properties. A plain object literal inherits from Object.prototype, whose built-in methods are not enumerable and therefore never show up. An object created with Object.create(parent) is different, because it inherits whatever enumerable properties the parent happens to have.
const parent = { role: 'reader' };
const post = Object.create(parent);
post.title = 'Hello';
for (const key in post) {
if (Object.hasOwn(post, key)) console.log('own:', key);
}
// own: title
console.log(Object.hasOwn(post, 'role')); // false
Without the guard, the loop would also report role, and that property belongs to the parent. The guard is cheap insurance, and it makes your intention obvious to the next person who reads the code.
How do I group records into an object?
Object.groupBy buckets an array of records by a key that you choose. It returns an object whose keys are the group names and whose values are arrays of the records that matched.
const orders = [
{ id: 1, status: 'paid' },
{ id: 2, status: 'pending' },
{ id: 3, status: 'paid' },
];
const byStatus = Object.groupBy(orders, function (order) {
return order.status;
});
console.log(byStatus.paid.length); // 2
console.log(Object.keys(byStatus)); // [ 'paid', 'pending' ]
It is the object-shaped sibling of the filter and reduce approaches from the arrays module, and it replaces a reduce that had to build a nested structure by hand. There are two caveats to know about. The group keys are always strings, and a record whose key is undefined ends up filed under the key 'undefined'. If you need a map instead of an object, which is worth doing when your keys might collide with names inherited from Object.prototype, use Map.groupBy, which arrived alongside it.
How do I turn a list of pairs back into an object?
Object.fromEntries is the inverse of Object.entries. It takes pairs and builds an object out of them.
const pairs = [['name', 'Ada'], ['role', 'admin']];
const user = Object.fromEntries(pairs);
console.log(user); // { name: 'Ada', role: 'admin' }
This is the standard way to build a lookup table from a list of records. You map each record to a pair, and then you convert all of the pairs in one step.
const users = [
{ id: 'a1', name: 'Ada' },
{ id: 'b2', name: 'Linus' },
];
const pairs = [];
for (const user of users) {
pairs.push([user.id, user.name]);
}
const byId = Object.fromEntries(pairs);
console.log(byId); // { a1: 'Ada', b2: 'Linus' }
Because the key becomes an object key, it is turned into a string. That is fine when your ids are numbers and you look them up with a string, but remember that byId[1] and byId['1'] are the same slot.
How do I sort the contents of an object?
Since Object.entries gives you arrays, the array methods apply directly, including sorting by value.
const scores = { Ada: 12, Grace: 20 };
const sorted = Object.entries(scores).sort(function (a, b) {
return b[1] - a[1];
});
console.log(sorted[0]); // [ 'Grace', 20 ]
Each pair is an array, so a[0] is the key and a[1] is the value, and that is why the comparator subtracts the second elements. If the indexes make the comparator hard to read, map the entries into objects such as { name, score } first and sort those instead. The extra line is usually worth it.
One more pattern is worth knowing. Object.values(obj) is the shortest route to a total, because the array methods work on the result. Adding up every value with Object.values(scores).reduce(function (a, b) { return a + b; }, 0) saves you from writing the loop by hand.
What should you remember when iterating objects?
| Method | Returns | Typical use |
|---|---|---|
Object.keys(obj) | Array of key names | Listing the fields of a record |
Object.values(obj) | Array of values | Collecting numbers to sum |
Object.entries(obj) | Array of [key, value] pairs | Looping when you need both |
Object.fromEntries(pairs) | A new object | Building a lookup table |
Object.groupBy(items, fn) | Object of arrays | Bucketing records by a field |
Object.hasOwn(obj, key) | A boolean | Ignoring inherited keys |
Try it yourself: write a file called iterate.js that starts with const scores = { Ada: 12, Linus: 9, Grace: 20 };. Print Object.keys and Object.values. Then use Object.entries to print each name with its score, and use Object.entries(...).sort(...) to find and print the highest scorer. Next, take an array of users that have an id and a name, and build a lookup object with Object.fromEntries so that you can fetch a name by its id in one line. Finally, take a list of orders and use Object.groupBy to bucket them by status, then loop over Object.entries of the grouped result to print how many orders sit in each group.