Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two arrays of keys and values to an object using underscore

Given two arrays, one with keys, one with values:

keys = ['foo', 'bar', 'qux'] values = ['1', '2', '3'] 

How would you convert it to an object, by only using underscore.js methods?

{    foo: '1',     bar: '2',    qux: '3' } 

I'm not looking for a plain javascript answer (like this).

I'm asking this as a personal exercise. I thought underscore had a method that was doing exactly this, only to find out it doesn't, and that got me wondering if it could be done. I have an answer, but it involves quite a few operations. How would you do it?

like image 257
Cristi Mihai Avatar asked Aug 30 '12 14:08

Cristi Mihai


People also ask

How do I merge two arrays together?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

What is the use of IS underscore array function?

Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays. Similar to without, but returns the values from array that are not present in the other arrays.


1 Answers

I know you asked for Underscore.js solutions, but you don't need it for this. Here's a oneliner using ES7 object spread operator and dynamic keys.

keys.reduce((obj, k, i) => ({...obj, [k]: values[i] }), {}) 
like image 82
ghirlekar Avatar answered Oct 06 '22 07:10

ghirlekar