kevin ternet kevin ternet - 1 year ago 63
Javascript Question

building a Map from 2 arrays of values and keys in Javascript

I wonder if there is an easy way to build a Map from an Array of keys and an Array of values.
for exemple if I have 2 Arrays

var keys = [0, 4, 2, 3, 1];
var values = ["first", "second", "third", "fourth", "fifth"];

and I intend to obtain this Map :

0 => 'first',
4 => 'second',
2 => 'third',
3 => 'fourth',
1 => 'fifth' }

of course I'm looking for something quicker than:

var myMap = new Map();
for (var i = 0 ; i < keys.length; i++)
myMap.set(keys[i], values[i]);

because it's O(n) and i seek something O(1)

Answer Source

You are looking for Object.assign (does not work on every user agent).

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var sum = ["first", "second", "third", "fourth", "fifth"],
    obj = Object.assign({}, sum);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download