-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"}
8
  • Similar question made for Java: stackoverflow.com/questions/12418334/… Commented Nov 9, 2018 at 16:29
  • @Pranay how you want the output? Commented Nov 9, 2018 at 16:31
  • You can start by writing some code. Commented Nov 9, 2018 at 16:32
  • 3
    What code have you tried already? What is your expected output? Do you want an actual JavaScript Map or just a plain object? (Since those have keys/values as well). Commented Nov 9, 2018 at 16:33
  • Expected output would be: {a: "1", b: "2", c: "3", d: "4"} Commented Nov 9, 2018 at 16:35

6 Answers 6

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]); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Come on, what is the point of downvoting an answer if you do not agree with the question?
@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.
Thanks for the answer!
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);

4 Comments

IMO map would be a better fit than forEach.
Why do you think that? :-)
Actually, I don't... changed my mind after thinking about it for a moment.
Thanks for the answer!
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)

Comments

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; }

1 Comment

Thanks for the answer!
0

When using lodash this is a one-liner:

_.zipObject(keys,values)

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.