Sub topic 9
Converting to Arrays, Objects, and JSON
Maps and Sets work well inside a running program. Much of the code around them expects something else: array methods such as map and filter, APIs that take plain objects, and JSON payloads sent over a network or saved to disk. This chapter covers the conversions between these forms and the information each one can lose.
This chapter assumes you know the Map and Set APIs, insertion-order iteration, and SameValueZero equality from earlier chapters. It also assumes you are comfortable with JSON.stringify, JSON.parse, and the spread operator.
The Conversion Map
Every conversion goes through one shape: an iterable of [key, value] pairs for Maps, or an iterable of values for Sets. Arrays, objects, and JSON all connect to Maps and Sets through that shape.
Maps and Sets to Arrays
Spreading a Map gives an array of [key, value] pairs in insertion order. Spreading a Set gives an array of its values. Array.from does the same thing and takes an optional mapping function, so you can convert and transform in one pass without building an intermediate array.
const prices = new Map([['apple', 1.2], ['pear', 0.8], ['plum', 2.5]]);
const colors = new Set(['red', 'green', 'blue']);
console.log([...prices]); // [['apple', 1.2], ['pear', 0.8], ['plum', 2.5]]
console.log([...prices.keys()]); // ['apple', 'pear', 'plum']
console.log([...prices.values()]); // [1.2, 0.8, 2.5]
console.log([...colors]); // ['red', 'green', 'blue']
const labels = Array.from(prices, ([name, price]) => `${name}: $${price}`);
console.log(labels); // ['apple: $1.2', 'pear: $0.8', 'plum: $2.5']
// Filter a Map by going through an array and back
const cheap = new Map([...prices].filter(([, price]) => price < 2));
console.log(cheap.size); // 2The last line shows a common idiom. Maps have no filter or map methods, so you convert the Map to an array, run the array method, and pass the result back to new Map.
Arrays to Maps and Sets
new Map(iterable) expects every item in the iterable to be an object, and it reads that object's 0 and 1 properties as the key and value. new Set(iterable) accepts any values. A mistake here fails right away with an error instead of producing bad data:
try {
new Map([1, 2, 3]);
} catch (err) {
console.log(err instanceof TypeError); // true: 1 is not an entry object
}
// Extra elements are ignored; missing ones become undefined
const m = new Map([['a', 1, 'ignored'], ['b']]);
console.log(m.get('a')); // 1
console.log(m.get('b')); // undefined
console.log(m.has('b')); // truePassing a string to new Set is another easy mistake. Strings are iterable, so new Set('hello') produces a Set of characters, {'h', 'e', 'l', 'o'}. To store the whole string, wrap it in an array: new Set(['hello']).
Objects and Maps
Object.entries turns an object into an entries array that new Map accepts. Object.fromEntries goes the other way and accepts any iterable of pairs, including a Map. Both directions have rules that can catch you out.
const sym = Symbol('secret');
const source = { b: 1, 2: 'two', a: 3, [sym]: 'hidden' };
const map = new Map(Object.entries(source));
console.log([...map.keys()]); // ['2', 'b', 'a']
console.log(map.get(2)); // undefined
console.log(map.get('2')); // 'two'
console.log(map.has(sym)); // false
const mixed = new Map([[1, 'number'], ['1', 'string'], [{ id: 7 }, 'object']]);
console.log(Object.fromEntries(mixed));
// { '1': 'string', '[object Object]': 'object' }Several things happened in that example:
Object.entriesreturns only own, enumerable, string-keyed properties. The symbol-keyed property was dropped. UseReflect.ownKeysif you need symbol keys too.- Object property order places integer-like keys first, in ascending order, and then the other string keys in insertion order. The Map inherits that order, so
'2'comes before'b'. - Every object key is a string. The number
2became'2', and the SameValueZero lookup with the number2fails. Object.fromEntriesconverts each key to a string.1and'1'collide and the later entry wins. An object key becomes'[object Object]', so any number of object keys collapse into one property.
JSON Serialization
JSON.stringify serializes an object's own enumerable properties. Map and Set store their data in internal slots, not in properties, so both serialize as '{}'. Nothing warns you about the lost data. The fix is to serialize an array instead:
const map = new Map([['theme', 'dark'], ['fontSize', 14]]);
const set = new Set(['js', 'css']);
console.log(JSON.stringify(map)); // '{}'
console.log(JSON.stringify(set)); // '{}'
console.log(JSON.stringify([...map])); // '[["theme","dark"],["fontSize",14]]'
console.log(JSON.stringify([...set])); // '["js","css"]'
const restoredMap = new Map(JSON.parse(JSON.stringify([...map])));
const restoredSet = new Set(JSON.parse(JSON.stringify([...set])));
console.log(restoredMap.get('fontSize')); // 14
console.log(restoredSet.has('css')); // trueNested Collections with a Replacer and Reviver
Spreading only converts the top level. When Maps and Sets sit deep inside other data, a replacer function can tag them during JSON.stringify and a reviver function can rebuild them during JSON.parse.
function replacer(key, value) {
if (value instanceof Map) return { __type: 'Map', entries: [...value] };
if (value instanceof Set) return { __type: 'Set', values: [...value] };
return value;
}
function 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 data = {
roles: new Map([['ana', new Set(['admin', 'dev'])]])
};
const json = JSON.stringify(data, replacer);
console.log(json);
// {"roles":{"__type":"Map","entries":[["ana",{"__type":"Set","values":["admin","dev"]}]]}}
const back = JSON.parse(json, reviver);
console.log(back.roles.get('ana').has('admin')); // trueThis works for nested data because JSON.stringify calls the replacer on each replacement value's children too, and JSON.parse calls the reviver from the innermost values outward. By the time the reviver rebuilds the outer Map, the inner Set already exists. The tag name __type is a convention you choose. If real data could contain an object with that property, pick a name that cannot clash.
What JSON Cannot Carry
Even with a correct replacer, JSON has limits that matter for collections:
const ids = new Set([NaN, -0, 1]);
const roundTrip = new Set(JSON.parse(JSON.stringify([...ids])));
console.log([...roundTrip]); // [null, 0, 1]
const owner = { id: 1 };
const byObject = new Map([[owner, 'data']]);
const copy = new Map(JSON.parse(JSON.stringify([...byObject])));
console.log(copy.get(owner)); // undefined
console.log([...copy.keys()][0]); // { id: 1 }, a different objectNaN becomes null and -0 becomes 0. If a Set held both null and NaN, the round trip would merge them into one value. Object keys come back as new objects with the same properties, so lookups by the original reference fail. Object identity is lost in serialization and cannot be restored by any reviver.
Copying Without Serialization
If you only need a copy inside the same program, skip JSON. new Map(map) and new Set(set) make shallow copies: the collection is new, but object keys and values are shared. structuredClone makes a deep copy, supports Map and Set natively, and keeps NaN, -0, and shared references within the cloned structure.
const original = new Map([['config', { debug: true }]]);
const shallow = new Map(original);
shallow.get('config').debug = false;
console.log(original.get('config').debug); // false: the value object is shared
const deep = structuredClone(original);
deep.get('config').debug = true;
console.log(original.get('config').debug); // false: deep copy is independent
console.log(deep instanceof Map); // trueWeakMap and WeakSet do not appear in any of these paths. They are not iterable, so they cannot be spread, passed to Array.from, or serialized, and structuredClone throws a DataCloneError for them.
Summary of Conversions
| Conversion | Method | What can be lost |
|---|---|---|
| Map to array | `[...map]`, `Array.from(map)` | Nothing |
| Array to Map | `new Map(pairs)` | Throws if an item is not an object |
| Object to Map | `new Map(Object.entries(obj))` | Symbol and non-enumerable keys; numeric keys become strings |
| Map to object | `Object.fromEntries(map)` | Key types; colliding keys; object keys |
| Set to or from array | `[...set]`, `new Set(array)` | Duplicates (by design) |
| Map or Set to JSON | Spread first, or use a replacer | `NaN`, `-0`, object identity, non-JSON values |
| In-memory copy | `new Map(m)`, `structuredClone(m)` | Shallow copy shares nested objects |
Exercise
A Map is built with new Map([[1, 'a'], ['1', 'b'], [true, 'c']]). What does Object.fromEntries return for it, and what does new Map(Object.entries(result)).get(1) return? Explain both.
Show answer
Object.fromEntries returns { '1': 'b', true: 'c' }. Every key is converted to a string, so 1 and '1' both become '1' and the later entry, 'b', overwrites 'a'. The boolean true becomes the string 'true'. Rebuilding a Map with Object.entries gives string keys only, so .get(1) returns undefined. SameValueZero does not treat the number 1 and the string '1' as equal.
Exercise
You store const state = { tags: new Set(['a', 'b']), counts: new Map([['a', 2]]) } in localStorage with localStorage.setItem('state', JSON.stringify(state)). After reloading, state.tags.has is not a function. What went wrong, and how do you fix it?
Show answer
JSON.stringify writes Maps and Sets as {}, so the saved string is {"tags":{},"counts":{}} and the data is gone. After parsing, tags is a plain empty object with no has method. To fix it, pass a replacer that converts Maps and Sets into tagged arrays when saving, such as { __type: 'Set', values: [...value] }, and a matching reviver to JSON.parse that rebuilds them when loading. Alternatively, store { tags: [...state.tags], counts: [...state.counts] } and rebuild each field with new Set and new Map.
Exercise
Why does structuredClone work on a Map of objects while JSON.parse(JSON.stringify([...map])) breaks lookups that use object keys?
Show answer
structuredClone copies the whole structure in memory. The keys in the clone are cloned objects that keep their place in the new Map's structure, and values such as NaN and -0 survive. The JSON round trip turns every key into text and parses it back into brand-new objects that have no link to the originals, so get(originalKey) compares references by SameValueZero and finds nothing. Neither approach keeps the original key objects, but only JSON also loses non-JSON values and shared references.