Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Map over an object's values in JavaScript

69 entries and fromEntries, there and back

fair

Convert a price list in kobo to naira by going out to entries, mapping, and coming back with Object.fromEntries. Do the same for a filter. Then show three things about the round trip: what happens to duplicate keys, what a Map gives you, and what integer-like keys do to the order.

Stuck? Three hints, smallest first
  1. 1. Object.entries(o).map(([k, v]) => [k, f(v)]) then Object.fromEntries is the whole of mapValues.
  2. 2. fromEntries takes any iterable of pairs, so a Map goes straight in.
  3. 3. Keys that look like non-negative integers are stored in ascending numeric order, before every string key, whatever order you wrote them in.

The answer

const kobo = { garri: 90000, rice: 450000, palmOil: 120000 };

const mapValues = (o, fn) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, fn(v, k)]));
const filterValues = (o, keep) => Object.fromEntries(Object.entries(o).filter(([k, v]) => keep(v, k)));

const naira = mapValues(kobo, (k) => k / 100);
const dear = filterValues(kobo, (k) => k >= 120000);
const shouted = Object.fromEntries(Object.entries(kobo).map(([k, v]) => [k.toUpperCase(), v]));
const roundTripped = same(Object.fromEntries(Object.entries(kobo)), kobo);

const stock = new Map([['garri', 12], ['rice', 4]]);
const fromMap = Object.fromEntries(stock);
const backToMap = [...new Map(Object.entries(fromMap))];

const duplicated = Object.fromEntries([['lga', 'Ikeja'], ['lga', 'Eti-Osa']]);
const numericOrder = Object.entries({ 10: 'ten', 2: 'two', zone: 'B', 1: 'one' });
const arrayEntries = Object.entries(['a', 'b']);
const valuesAndKeys = [Object.keys(kobo).length, Object.values(kobo).reduce((a, b) => a + b, 0)];

console.log('naira  :', naira);
console.log('filter :', dear, '| shouted:', shouted);
console.log('map    :', fromMap, backToMap);
console.log('dupes  :', duplicated, '| order:', numericOrder.map(([k]) => k));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('entries out, map, fromEntries back is mapValues in one line', naira, { garri: 900, rice: 4500, palmOil: 1200 });
test('the same shape filters, because a pair carries the key too', dear, { rice: 450000, palmOil: 120000 });
test('and the key is just as mappable as the value', Object.keys(shouted), ['GARRI', 'RICE', 'PALMOIL']);
test('a round trip with no change gives back an equal object', roundTripped, true);
test('fromEntries eats any iterable of pairs, so a Map goes straight in', [fromMap, backToMap], [{ garri: 12, rice: 4 }, [['garri', 12], ['rice', 4]]]);
test('a repeated key is not an error: the last pair wins, silently', duplicated, { lga: 'Eti-Osa' });
test('integer-like keys come out in numeric order, ahead of every string key', numericOrder.map(([k]) => k), ['1', '2', '10', 'zone']);
test('entries on an array gives string indices, which fromEntries keeps as strings', [arrayEntries, Object.fromEntries(arrayEntries)], [[['0', 'a'], ['1', 'b']], { 0: 'a', 1: 'b' }]);
test('keys and values are the same walk, projected differently', valuesAndKeys, [3, 660000]);

Object.entries and Object.fromEntries turn an object into something array methods can work on and then turn it back. That pairing replaces most hand-written for...in loops with an accumulator: mapValues, filterValues, key renaming and inversion are all the same three lines with a different callback.

Two facts to hold on to. The round trip is lossy in the ways spread is not: only own enumerable string keys make it through, so symbol keys, non-enumerable properties and the prototype are all left behind. And fromEntries has no opinion about duplicates — the last pair for a key wins with no warning, which is either exactly the merge you wanted or a bug you will not see until two rows share an id.

The ordering assertion is the one that catches people building objects keyed by number. Integer-like keys are held in ascending numeric order and listed before any string key, so an object keyed 10, 2, 1 reads back 1, 2, 10. If insertion order is part of your meaning, use a Map, where a key is whatever you put in and the order is the order you put it.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.