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

14,320

Solution 1

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.

Solution 2

Also if you have a single value list or want to make sure it IS unique you can use the index supplied like this:

obj.map((item, index) => 
   ...
)}
Share:
14,320
Joshua Rajandiran
Author by

Joshua Rajandiran

Updated on June 25, 2022

Comments

  • Joshua Rajandiran
    Joshua Rajandiran almost 2 years

    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?

  • Nina Scholz
    Nina Scholz almost 8 years
    why map with no return and assingment/later use of array?