4

I have an array of key value pairs where each key has an another array of constant length (i.e., 2) as the value. How can I add the entire array to a Map() without just doing Map.set(key, value) for every pair?

I know that while creating a Map() instance I could pass an iterable like an array to it ex: let x = new Map(arr); But this is not supported in IE 11 as per the documentation here. So, could anyone help me out with an alternate implementation.

At the end of the day, I just want to be able to access the two values with a string key. If there is an another way I could implement, please guide me.

Here is the example:

I created a key value mapping array as follows:

let arr = [
        ['ar', ['cl', 'bl']],
        ['bs', ['kl', 'ml']],
        ['cs', ['rk', 'uk']],
        ['da', ['mk', 'ak']]
    ];
let map = new Map(arr); // This isn't working. 

Thank you.

0

2 Answers 2

5

If you need to support browsers where the Map is not implemented, just use ordinary object, where the 1st array item will be keys & 2nd (the sub-array) values:

var arr = [
        ['ar', ['cl', 'bl']],
        ['bs', ['kl', 'ml']],
        ['cs', ['rk', 'uk']],
        ['da', ['mk', 'ak']]
    ];

var map = arr.reduce(function (obj, item) {
    obj[item[0]] = item[1];
    return obj;
}, {});

console.log(map['ar'], map.bs);

Or ES2015 approach (won't work in IE11):

const map = arr.reduce((obj, item) => ({
    ...obj,
    [item[0]]: item[1],
}), {});

If you want to access the subarray by the string key, you'd have to convert it from array anyways.

If you'd want to use Map, then (apart from fixing typos in your array definition) you'll extract the contents by Map.prototype.get function:

var map = new Map(arr);
console.log(map.get('bs'));

If you don't want to create a new object, another approach could be using Array.filter:

arr.filter(function (item) { return item[0] === 'ar' })[0][1];
arr.filter((item) => item[0] === 'ar')[0][1]; // ES2015

(potentially wrapped in a function)

2
  • If I don't have the key in the object. How could I handle that situation?
    – Tums
    Commented Feb 2, 2018 at 16:23
  • Not sure what do you mean, like having just the subarray ['cl', 'bl'] instead of ['ar', ['cl', 'bl']]? Then keep it an ordinary array, from which you can select by index, or you can convert it to an object e.g. by making the 1st item a key like { cl: ['cl', 'bl'], kl: ['kl', 'ml'] }. Commented Feb 2, 2018 at 16:32
1

You can use a object

let obj = 
{ ar:['cl', 'bl'],
  bs:['kl', 'ml'],
  cs:['rk', 'uk'],
  da:['mk', 'ak']
};
console.log(obj['bs'][1]); // displays 'ml'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.