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?
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.
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.
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] }), {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With