-2

I have two string arrays keys and values:

let keys = [a,b,c,d]
let values = [1,2,3,4]

How to convert them into a map?

Expected output would be:

{a: "1", b: "2", c: "3", d: "4"}
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
Pranay
  • 498
  • 1
  • 4
  • 16
  • Similar question made for Java: https://stackoverflow.com/questions/12418334/converting-string-arrays-into-map – Pranay Nov 09 '18 at 16:29
  • @Pranay how you want the output? – Jameel Moideen Nov 09 '18 at 16:31
  • You can start by writing some code. – slider Nov 09 '18 at 16:32
  • 3
    What code have you tried already? What is your expected output? Do you want an actual JavaScript [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) or just a plain object? (Since those have keys/values as well). – Herohtar Nov 09 '18 at 16:33
  • Expected output would be: {a: "1", b: "2", c: "3", d: "4"} – Pranay Nov 09 '18 at 16:35
  • A "map", as you've shown it, is an object in JS. – evolutionxbox Nov 09 '18 at 16:36
  • Solved using one answer. Will accept answer in 1 min. (By the way, I don't understand why so much down-voting going on?) Obviously from the question you guys can understand java-script is not my choice of coding languages and thus comes the seemingly stupid questions.. – Pranay Nov 09 '18 at 16:43
  • @Pranay Questions get downvoted for not including things that are needed for people to be able to answer -- such as what your desired output/result is, example code, etc. Take a look at [How to ask](https://stackoverflow.com/help/how-to-ask) to understand how to write good questions. People also tend to downvote if you don't show any attempt at solving the problem yourself, as SO is not a code writing service. – Herohtar Nov 09 '18 at 16:48

6 Answers6

8

you can use Map in ES6

var myMap = new Map();

// setting the values
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');

your answer :

for (let i = 0; i < keys.length; i++) {
     myMap.set(keys[i], values[i]); 
}
Yashar Panahi
  • 2,816
  • 1
  • 16
  • 22
  • 1
    Come on, what is the point of downvoting an answer if you do not agree with the question? – Loredra L Nov 09 '18 at 16:33
  • 3
    @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs. – Adrian Nov 09 '18 at 16:43
  • Thanks for the answer! – Pranay Nov 09 '18 at 16:44
3

Firstly create an object. Then loop through your array and add the keys and values to the object.

let keys = ['a','b','c','d'];
let values = [1,2,3,4];

let obj = {};

keys.forEach((key, index) => {
  obj[key] = values[index]
});

console.log(obj);
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
1

You can use array reduce on any of the array and use index to retrieve value from another array

let keys = ['a', 'b', 'c', 'd'];
let values = [1, 2, 3, 4];
let k = keys.reduce((acc, curr, index) => {
  acc[curr] = values[index]
  return acc;
}, {});

console.log(k)
brk
  • 48,835
  • 10
  • 56
  • 78
1

First of all, you need to declare your string arrays properly.

let keys = ['a', 'b', 'c', 'd'];
let values = ['1', '2', '3', '4'];

var zip = (target, ...arr) => {
  if (target == null) throw Error('Target is undefined');
  if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
  if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
  if (Array.isArray(target)) {
    arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
  } else if (typeof target === 'object') {
    arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
  } else {
    throw Error('Unsupported target type');
  }
  return target;
}

var zipObj = (...arr) => zip.call(null, {}, ...arr);
var zipArr = (...arr) => zip.call(null, [], ...arr);

//console.log(zip({}, keys, values));
console.log(zipObj(keys, values)); // Zip object

//console.log(zip([], keys, values));
console.log(zipArr(keys, values)); // Zip array
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

When using lodash this is a one-liner:

_.zipObject(keys,values)
alexloehr
  • 1,773
  • 1
  • 20
  • 18
0

This should do the trick:

let keys = ['a','b','c','d']
let values = [1,2,3,4]
let mapped = keys.reduce((accumulator, current, index) => {
    accumulator[current] = values[index];
    return accumulator;
}, {});

console.log(mapped)
// Result should be:
{a: 1, b: 2, c: 3, d: 4}

Reduce is a powerful method that can be used for all sorts of tasks.

Here we're "reducing" the given values of keys into an object where keys are the key and values are the correlating values.

The first parameter in reduce is a callback function that you need to pass along at minimum accumulator and current variables (can have different names); the other parameters are index and array which represent the current index of the iteration and the original array that is being iterated.

The second parameter is the initial value of the accumulator; by default it will be the first current value but in our case we set it to {} so we can treat it as an object.

I hope this helps!