Cristi Mihai Cristi Mihai - 1 year ago 163
Javascript Question

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?

Answer Source

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.

_.object = function(list, values) {
    if (list == null) return {};
    var result = {};
    for (var i = 0, l = list.length; i < l; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
    return result;