Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Convert a Map or Set to an array in JavaScript

61 Maps and Sets to arrays and back

fair

Convert a Map to pairs, to a plain object and back again, map over it with Array.from, and filter it. Then show what JSON.stringify makes of a Map and a Set, and tally a list with a Map.

Stuck? Three hints, smallest first
  1. 1. [...map] gives pairs; Object.fromEntries(map) gives an object; new Map(Object.entries(obj)) comes back.
  2. 2. Array.from takes a mapping function, and the element it passes is the [key, value] pair, so destructure it.
  3. 3. Neither a Map nor a Set has own enumerable properties, which decides what JSON can see.

The answer

const prices = new Map([['gari', 250000], ['rice', 480000]]);

const asPairs = [...prices];
const asObject = Object.fromEntries(prices);
const backToMap = new Map(Object.entries(asObject));
const roundTripped = [...backToMap];
const keysArray = Array.from(prices.keys());
const labelled = Array.from(prices, ([name, kobo]) => `${name}: ₦${kobo / 100}`);

const stock = new Set(['gari', 'rice']);
const jsonAttempts = [JSON.stringify(prices), JSON.stringify(stock)];
const jsonAfterConverting = [JSON.stringify(Object.fromEntries(prices)), JSON.stringify([...stock])];

const tally = new Map();
for (const area of ['Ikeja', 'Yaba', 'Ikeja']) tally.set(area, (tally.get(area) ?? 0) + 1);
const tallyAsObject = Object.fromEntries(tally);

const dear = new Map([...prices].filter(([, kobo]) => kobo > 300000));
const doubled = new Map([...prices].map(([name, kobo]) => [name, kobo * 2]));

console.log('pairs     :', asPairs);
console.log('object    :', asObject, '| back to a Map:', roundTripped);
console.log('labelled  :', labelled);
console.log('JSON      :', jsonAttempts, '<- both empty');
console.log('converted :', jsonAfterConverting);
console.log('tally     :', tallyAsObject, '| filtered:', [...dear]);

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('spreading a Map gives its pairs', asPairs, [['gari', 250000], ['rice', 480000]]);
test('fromEntries turns those pairs into a plain object', asObject, { gari: 250000, rice: 480000 });
test('and Object.entries takes it back to a Map unchanged', roundTripped, [['gari', 250000], ['rice', 480000]]);
test('Array.from works on any of its iterators', keysArray, ['gari', 'rice']);
test('and its mapping function receives each pair', labelled, ['gari: ₦2500', 'rice: ₦4800']);
test('JSON.stringify finds nothing in a Map or a Set', jsonAttempts, ['{}', '{}']);
test('so convert before serialising', jsonAfterConverting, ['{"gari":250000,"rice":480000}', '["gari","rice"]']);
test('a Map is the natural tally, and fromEntries reports it', tallyAsObject, { Ikeja: 2, Yaba: 1 });
test('filtering or mapping a Map means going out to an array and back', [[...dear], [...doubled]], [[['rice', 480000]], [['gari', 500000], ['rice', 960000]]]);

Object.fromEntries accepts a Map directly, and new Map accepts an array of pairs, so the round trip is two calls with no loop. The one asymmetry: keys that were not strings come back as strings through the object, so a Map keyed by numbers does not survive the detour intact.

The JSON pair is the assertion to remember. A Map keeps its contents in internal slots, not in own enumerable properties, so JSON.stringify(map) is '{}' — no error, no warning, just an empty object arriving at your API. Same for a Set. Convert first, every time, and on the way back rebuild the Map rather than working with the plain object, or you inherit the key-order and prototype problems the Map was chosen to avoid. Note also that a Map has no map or filter of its own: spread, use the array methods, and construct a new Map from the result.

Newsletter

New writing, when it lands.

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