Sub topic 9
Converting to Arrays, Objects, and JSON
This chapter assumes you know how to create and iterate Maps and Sets, and that you are comfortable with the spread operator, Object.entries, and JSON.stringify. Map and Set are built for fast lookups. Most other APIs expect arrays, plain objects, or JSON strings, so you will often convert between these forms.
Arrays: The Common Format
Maps and Sets are iterable, so the spread operator and Array.from both turn them into arrays. A Map becomes an array of [key, value] pairs, and a Set becomes an array of its values. Both keep insertion order.
const scores = new Map([['ana', 90], ['ben', 75]]);
const ids = new Set([3, 1, 2]);
console.log([...scores]); // [['ana', 90], ['ben', 75]]
console.log([...scores.keys()]); // ['ana', 'ben']
console.log(Array.from(scores.values())); // [90, 75]
console.log([...ids]); // [3, 1, 2]
// Array.from takes a mapping function as its second argument
console.log(Array.from(ids, (id) => id * 10)); // [30, 10, 20]The constructors work the other way. new Map(iterable) takes any iterable of pairs, and new Set(iterable) takes any iterable of values.
Maps and Plain Objects
Object.entries returns an object's own enumerable string-keyed properties as pairs, which is exactly the input new Map expects. Object.fromEntries accepts any iterable of pairs, Maps included.
const settings = { theme: 'dark', fontSize: 14 };
const map = new Map(Object.entries(settings));
const backToObject = Object.fromEntries(map);
console.log(backToObject); // { theme: 'dark', fontSize: 14 }Going from Map to object can lose information. Object keys can only be strings or symbols, so every other key is converted to a string.
const mixed = new Map([[1, 'one'], ['1', 'string one'], [{}, 'obj']]);
console.log(Object.fromEntries(mixed));
// { '1': 'string one', '[object Object]': 'obj' }The number 1 and the string '1' collapsed into one property, and the later value overwrote the earlier one. The object key became the string '[object Object]'.
JSON Serialization
JSON.stringify only serializes enumerable own properties. Maps and Sets keep their data in internal slots, not in properties, so they serialize as empty objects with no error.
const map = new Map([['theme', 'dark'], ['fontSize', 14]]);
console.log(JSON.stringify(map)); // '{}'
console.log(JSON.stringify(new Set([1, 2]))); // '{}'
console.log(JSON.stringify([...map])); // '[["theme","dark"],["fontSize",14]]'
const restored = new Map(JSON.parse(JSON.stringify([...map])));
console.log(restored.get('theme')); // 'dark'When the collections sit inside larger data, use a replacer and a reviver to tag them:
const replacer = (key, value) => {
if (value instanceof Map) return { __type: 'Map', entries: [...value] };
if (value instanceof Set) return { __type: 'Set', values: [...value] };
return value;
};
const reviver = (key, value) => {
if (value && value.__type === 'Map') return new Map(value.entries);
if (value && value.__type === 'Set') return new Set(value.values);
return value;
};
const state = { users: new Map([['ana', { tags: new Set(['admin']) }]]) };
const text = JSON.stringify(state, replacer);
const copy = JSON.parse(text, reviver);
console.log(copy.users.get('ana').tags.has('admin')); // trueThe reviver runs from the innermost values outward, so nested Sets are rebuilt before the Map that holds them.
Common Errors
| Mistake | Result | Fix |
|---|---|---|
| `JSON.stringify(map)` | `'{}'`, data lost silently | Stringify `[...map]` |
| `Object.fromEntries` on non-string keys | Keys coerced, possible collisions | Keep the Map, or serialize entries |
| `new Map(obj)` | TypeError: object is not iterable | `new Map(Object.entries(obj))` |
| Object keys inside entries JSON | Restored as new objects, not the originals | Use string or number IDs as keys |
Exercise
You have const m = new Map([[true, 'yes'], ['true', 'string']]);. What does Object.fromEntries(m) return, and how would you serialize m to JSON without losing either entry?
Show answer
It returns { true: 'string' }, because the boolean key true is converted to the string 'true' and the later entry overwrites it. Serialize with JSON.stringify([...m]), which gives '[[true,"yes"],["true","string"]]', and restore with new Map(JSON.parse(text)).
Exercise
Why does JSON.stringify(new Set(['a', 'b'])) produce '{}' instead of throwing an error?
Show answer
A Set stores its values in internal slots, not in enumerable own properties, and it has no toJSON method. JSON.stringify sees an object with no properties and writes an empty object.