Looping Over Objects
You cannot loop over a plain object with for...of. Try it, and you get an error:
const stock = { laptop: 12, mouse: 50 };
for (const item of stock) {
console.log(item);
}
Output:
/box/index.js:2
for (const item of stock) {
^
TypeError: stock is not iterable
at Object.<anonymous> (/box/index.js:2:20)
"Not iterable" means "this cannot be looped over directly". Instead, three helper functions turn an object into an array. You already know how to loop over arrays.
const stock = { laptop: 12, mouse: 50 };
console.log(Object.keys(stock));
console.log(Object.values(stock));
console.log(Object.entries(stock));
Output:
[ 'laptop', 'mouse' ]
[ 12, 50 ]
[ [ 'laptop', 12 ], [ 'mouse', 50 ] ]
Object.keys gives the keys, and Object.values gives the values. Object.entries gives both, as a list of pairs. Each pair is a small array: the key first, then the value.
To visit every key and value, loop over the entries. Use array destructuring from the last lesson to unpack each pair right in the loop:
<!-- continues -->for (const [product, count] of Object.entries(stock)) {
console.log(`${product}: ${count}`);
}
Output:
laptop: 12
mouse: 50
Now product and count are normal variables inside the loop. You can also use these arrays with the array methods you know. Here reduce adds up all the values:
const values = Object.values(stock);
console.log(values.reduce((sum, n) => sum + n, 0));
Output:
62
What order do the keys come in? Usually it is the order you added them. But there is one exception. Keys that look like whole numbers come first, sorted from small to large:
const names = { boss: "Alice", 30: "Emma", 7: "Bob" };
names.intern = "Dave";
console.log(Object.keys(names));
Output:
[ '7', '30', 'boss', 'intern' ]
The key boss was added first, but 7 and 30 still come before it. All other keys keep the order in which you added them. Also notice the quotes in '7'. Object keys are always strings, even when you write them as numbers. If you need a different order, get the entries and sort that array before you loop.
You may also see for...in (with in, not of) in older code. It loops over the keys of an object. In new code, use Object.keys or Object.entries with for...of instead. Then the same kind of loop works for arrays and for objects.
In the exercise, add a product to the stock, print every entry, and add up the counts.