Object.groupBy Missing Buckets After JSON: Fix the Lookup
Contents
An Object.groupBy() result can work in memory and break after a JSON round trip. For example, groups[key] ?? [] returns an empty array for a missing "toString" group in the original result. After parsing the JSON, the same expression returns an inherited function. If the caller then runs .map() on the bucket, it throws a TypeError.
Check for an own property before reading the bucket. This keeps the same lookup behavior on both sides of the JSON boundary.
Find what changed during the round trip
ECMAScript defines Object.groupBy() to create an object with a null prototype. When an input row has the group label "hasOwnProperty", that name holds a bucket array. When no row has the label "toString", reading that key returns undefined.
Parsing the serialized object creates an ordinary object. Spreading into { ...groups } also creates an ordinary object. Both retain the group entries in this example and inherit Object.prototype.toString. The nullish fallback only checks whether the value it read is null or undefined, so it accepts the inherited function.
Reproduce the lookup and verify the fix
Save the following as groups.mjs and run node groups.mjs. The fixture uses string group labels and JSON-compatible rows. It was checked with Node.js 24.13.0 on macOS arm64.
import assert from 'node:assert/strict';
const rows = [ { id: 1, team: 'design' }, { id: 2, team: 'hasOwnProperty' },];
const groups = Object.groupBy(rows, row => row.team);const spread = { ...groups };const parsed = JSON.parse(JSON.stringify(groups));
function readBucket(dictionary, key) { return Object.hasOwn(dictionary, key) ? dictionary[key] : [];}
assert.equal(Object.getPrototypeOf(groups), null);assert.deepEqual(groups.toString ?? [], []);
for (const copy of [spread, parsed]) { assert.equal(Object.getPrototypeOf(copy), Object.prototype); assert.equal(copy.toString ?? [], Object.prototype.toString); assert.throws(() => (copy.toString ?? []).map(row => row.id), TypeError);}
for (const dictionary of [groups, spread, parsed]) { assert.deepEqual(readBucket(dictionary, 'missing'), []); assert.deepEqual(readBucket(dictionary, 'toString'), []); assert.deepEqual(readBucket(dictionary, 'constructor'), []); assert.deepEqual(readBucket(dictionary, 'design').map(row => row.id), [1]); assert.deepEqual( readBucket(dictionary, 'hasOwnProperty').map(row => row.id), [2], );}
console.log('Bucket lookups passed for the original, spread, and JSON objects.');Object.hasOwn() works with both prototypes and still finds the real "hasOwnProperty" group. Use the same check anywhere the caller looks up a dynamic label. If a payload comes from an external source, validate that its own values are bucket arrays before treating it as a grouped result.
For the separate case where numeric and string labels such as 7 and "7" need distinct buckets, use Map.groupBy and JSON entries.
References