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?
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.
What you are looking for is the zip function.
zip function
Edit: It doesn't create an object but it does combine the array by creating a sub array
There's no function that exactly does what you want. But you can use the result of zip to create your object.
Cleanest is
Or, use
_.reduce
, but if you're using underscore you already have_.object
.How about:
To be complete: another approach could be:
For the record, without underscore you could extend Array.prototype:
See jsfiddle
Given that this is 4 years old, and Lodash has more or less taken the place of Underscore, I thought I would share this solution using Lodash:
Simple and clean.
What you need to use is the _.object method of underscore js. If object method is not present in your version of underscore.js then you will have to manually add this method to it.