Loop through object keys and values in JavaScript
Beginner · 4 min read
An object stores values under names. A fare table, a price list, a settings panel and a word count are all objects: each name (the key) points at one value. Sooner or later you need to walk through every pair: to print a list, to add up the amounts, or to count how many there are.
In this tutorial you will take a small table of bus fares and list its stops, list its amounts, total them and count them. Along the way you will meet Object.keys, Object.values and Object.entries, and the for...in loop. You need to know what an object and an array are, and how a for...of loop works.
An object is not an array
An array has positions (0, 1, 2) and a length. An object has names and no length. That means you can't loop over an object the way you loop over an array. for (const x of fares) on a plain object throws a TypeError.
The fix is to turn the object into an array first. JavaScript gives you three functions for that:
Object.keys(obj)gives an array of the keys.Object.values(obj)gives an array of the values.Object.entries(obj)gives an array of[key, value]pairs.
Once you have an array, every array tool you already know works on it.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
82 Walk an object with keys, values and entries
easyGiven a table of fares keyed by stop, list the stops, list the amounts, total them, and count how many there are.
Stuck? Three hints, smallest first
- 1.
Object.keys,Object.valuesandObject.entrieseach give you an array. - 2. Destructure in the loop head:
for (const [stop, kobo] of Object.entries(fares)). - 3. An object has no
length. Count the keys instead.
Step 1: list the keys
The fares are in kobo (100 kobo make one naira). The underscores in 200_00 only make the number easier to read.
const fares = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const stops = Object.keys(fares);
console.log(stops); // [ 'yaba', 'ikeja', 'lekki' ]
The keys come back in the order they were written in the object. Keys are always text (strings), which is why they print in quotes.
Step 2: list the values
const fares = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const amounts = Object.values(fares);
console.log(amounts); // [ 20000, 35000, 50000 ]
The values come back in the same order as the keys, so stops[0] and amounts[0] belong together.
Step 3: keys and values together
Most of the time you want both at once. Object.entries gives you one small array per pair:
const fares = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const pairs = Object.entries(fares);
console.log(pairs[0]); // [ 'yaba', 20000 ]
let total = 0;
for (const [stop, kobo] of Object.entries(fares)) total += kobo;
console.log(total); // 105000
Look at the loop head: const [stop, kobo]. Each item is a pair like ['yaba', 20000], and the square brackets unpack it into two names. This is called destructuring. Without it you would write pair[0] and pair[1], which says much less about what the values mean.
Step 4: the for...in loop
There is also a loop made for objects. for...in gives you one key per turn, and you read the value with brackets:
const fares = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const lines = [];
for (const stop in fares) lines.push(stop + '=' + fares[stop]);
console.log(lines); // [ 'yaba=20000', 'ikeja=35000', 'lekki=50000' ]
It reaches the same keys as Object.keys, without building an array first. You have to write fares[stop], not fares.stop: the dot would look for a key literally called stop.
Step 5: count the keys
Here is the natural wrong turn. You want the number of stops, so you reach for length:
const fares = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
console.log(fares.length); // undefined
console.log(Object.keys(fares).length); // 3
fares.length doesn't throw an error. It quietly means "there is no key called length", so you get undefined. To count, turn the keys into an array and ask the array for its length.
Step 6: a surprise in the order
Keys usually come back in the order you wrote them. There is one exception: keys that look like whole numbers always come first, in number order.
console.log(Object.keys({ 10: 'ten', 2: 'two' })); // [ '2', '10' ]
console.log(Object.keys({ b: 1, 5: 'five', a: 2 })); // [ '5', 'b', 'a' ]
10 was written first but comes back second. If your keys are things like years or ids and the order matters, keep that in mind, or use a Map, which always keeps the order you added things.
The full solution
The answer panel lists the keys and values, builds the entries, totals the fares with a destructuring loop, walks them again with for...in, and counts the stops. Its checks also cover fares.length being undefined and the number-key order. Press Run to see the output.
const fares = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const stops = Object.keys(fares);
const amounts = Object.values(fares);
const pairs = Object.entries(fares);
let total = 0;
for (const [stop, kobo] of Object.entries(fares)) total += kobo;
// for...in reaches the same keys, one at a time, without building an array.
const lines = [];
for (const stop in fares) lines.push(stop + '=' + fares[stop]);
const count = Object.keys(fares).length;
console.log(pairs);
console.log('total:', total, 'across', count, 'stops');
console.log('fares.length is', fares.length);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the keys, in the order they were written', stops, ['yaba', 'ikeja', 'lekki']);
test('the values, in the same order', amounts, [20000, 35000, 50000]);
test('entries pairs them up', pairs[0], ['yaba', 20000]);
test('destructuring in the loop head reads well', total, 105000);
test('for...in reaches the same keys', lines, ['yaba=20000', 'ikeja=35000', 'lekki=50000']);
test('an object has no length', fares.length, undefined);
test('so count the keys', count, 3);
test('but integer-like keys come back in numeric order, not insertion order', Object.keys({ 10: 'ten', 2: 'two' }), ['2', '10']);
The three Object functions cover almost everything a beginner needs from an object: keys to list, values to total, entries to do both at once. All three return arrays, so every array method is available afterwards — Object.values(fares).reduce(...) replaces the loop above entirely.
fares.length being undefined catches people out because it does not throw; it silently means "no such key". And key order is insertion order except for keys that look like array indices, which are always visited in ascending numeric order. If you need dependable ordering across mixed keys, or keys that are not strings, use a Map.
Common mistakes
- Using
for...ofdirectly on an object. A plain object can't be walked that way and throws aTypeError. Wrap it inObject.entriesfirst. - Asking an object for its
length. It givesundefinedwithout any error. UseObject.keys(obj).length. - Writing
fares.stopinside afor...inloop. The dot reads a key named "stop". Usefares[stop]to read the key held in the variable.
Try it yourself
- Replace the total loop with one line:
Object.values(fares).reduce((sum, kobo) => sum + kobo, 0). - Print each stop as
yaba: ₦200.00, dividing the kobo by 100 and usingtoFixed(2). - Find the most expensive stop. Walk
Object.entries(fares)and keep the pair with the biggest value.