Skip Jack Skip Jack - 4 months ago 4
Javascript Question

How should I map numbers to text in JSON?

What is the best practice when it comes to mapping numbers to text in JSON? A JavaScript map would be perfect as I can use numbers for keys, which I can't do with objects:

let map = new Map();

map.set(1, 'describe 1');
map.set(2, 'describe 2');

... and so on. However you can't use maps in json, as far as I know. Is the best option really just to use an array of arrays?

[ 1, 'describe 1' ],
[ 2, 'describe 2' ]


JSON stands for "JavaScript Object Notation" and is a subset of Javascript--specifically the subset that is used for writing out objects. The map you're typing creates an object. That object that the map.set function outputs is what you're getting at. You can see it by doing this.

let map = new Map();

map.set(1, 'describe 1');
map.set(2, 'describe 2');

I think that you want your numbers to be strings, in which case you can do this:

let map = new Map();

map.set('1', 'describe 1');
map.set('2', 'describe 2');

However, if your numbers are intended to identify the indexes of items on an array, you might be going for this:

[null, 'describe 1', 'describe 2']

Either way, you'll be able to see it with JSON.stringify

For more evidence, here's what Chrome outputs with your inputs:

> let map = new Map();
> map.set(1, 'describe 1');
Map {1 => "describe 1"}
> map.set(2, 'describe 1');
Map {1 => "describe 1", 2 => "describe 1"}

Which would look like:

{ 1: 'describe 1', 2: 'describe 2' }

as a Javascript Object (i.e. JSON)

For more information on JSON, check out