Reputation: 589
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.
Upvotes: 4
Views: 2995
Reputation: 1440
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)
Upvotes: 5
Reputation: 704
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'
Upvotes: 1