Joshua Rajandiran Joshua Rajandiran - 3 months ago 7
JSON Question

how to create a map with unique keys from a parsed object in javascript es6/2015?

Lets say I receive a parsed json like below:


The keys are the same which is

How do I make each
unique so that the map is usable?'


Results I want:

let myMap = {}; //I declare my variable
//Then I fetch a json and parse it
.then(function(response) {
return response.json(); //parse the json string
}).then(function(json) {
myMap = json; //set it to myMap to be used

For some reason I having duplicate keys although you guys said the json is unique. Do I have to set the json string to
first and then only parse it?


Basically you can use an Object as hash table

var data = [{ "a": 1 }, { "a": 2 }, { "a": 3 }],
    object = Object.create(null);

data.forEach(function (el) {
    object[el.a] = el;


Or a Map

var data = [{ "a": 1 }, { "a": 2 }, { "a": 3 }],
    map = new Map;

data.forEach(function (el) {
    map.set(el.a, el);


The advantage of Map over an Object is, the key can be anything. The key is not converted to string. Maps can have an object or other primitive or not primitive values as key.