JavaScript Map.groupBy and JSON: Preserve Numeric and String Keys
Contents
If your input contains both the number 7 and the string "7" as IDs, Map.groupBy() keeps them in separate groups. The groups can still disappear when you send the result as JSON. Serialize the Map as an array of entries to preserve the type of each ID and recover both groups on the receiving side.
Find where the group disappears
Object.groupBy()converts grouping keys to property keys. Both IDs become the property"7", and its bucket contains both rows.Map.groupBy()keeps these IDs distinct. CallingJSON.stringify()directly on the resulting Map produces{}because its entries are stored separately from enumerable own properties.Object.fromEntries(map)converts the keys to property keys again. In this fixture the string ID comes second, so its entire bucket replaces the numeric bucket.
The last two cases can send valid JSON while silently changing the data. A check that only calls JSON.parse() misses both failures.
Round-trip the entries and test both lookups
Save this as groups.mjs and run node groups.mjs. The fixture was checked with Node.js 24.13.0 on macOS. It compares the two grouping APIs, then checks the payload after each conversion.
import assert from 'node:assert/strict';
const rows = [ { id: 7, label: 'numeric' }, { id: '7', label: 'text' },];
const objectGroups = Object.groupBy(rows, row => row.id);const mapGroups = Map.groupBy(rows, row => row.id);
assert.deepEqual(objectGroups['7'], rows);assert.equal(mapGroups.size, 2);assert.equal(JSON.stringify(mapGroups), '{}');
const collapsed = JSON.parse(JSON.stringify(Object.fromEntries(mapGroups)));assert.deepEqual(collapsed, { '7': [rows[1]] });
const restored = new Map(JSON.parse(JSON.stringify([...mapGroups])));assert.equal(restored.size, 2);assert.deepEqual(restored.get(7), [rows[0]]);assert.deepEqual(restored.get('7'), [rows[1]]);console.log('Both typed groups survived the entry-array round trip.');The last line prints Both typed groups survived the entry-array round trip. after the receiver retrieves the original numeric and string buckets separately.
Use this payload shape when both sides can accept an array of [id, rows] pairs and the IDs are strings or finite numbers, as in the fixture. An API that requires a JSON object needs a different schema, such as a field for the ID type alongside the ID and rows. If the types are supposed to refer to the same entity, normalize them before grouping so both rows enter the same bucket deliberately. Key type is a separate concern from numeric property ordering.
References: