Joshua Rajandiran Joshua Rajandiran - 5 months ago 13
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:

[{"a":1},{"a":2},{"a":3}]


The keys are the same which is
a
.

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

EDIT1:

Results I want:

let myMap = {}; //I declare my variable
//Then I fetch a json and parse it
fetch(link)
.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
myMap
first and then only parse it?

Answer

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;
});

console.log(object);

Or a Map

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

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

console.log(map.get(1));

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.