merge two arrays of keys and values to an object u

2020-01-31 01:03发布

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?

8条回答
再贱就再见
2楼-- · 2020-01-31 01:38

Using ES6:

let numbers = [1, 2, 3],
    names = ["John", "Mike", "Colin"];

let a = Object.assign({}, ...numbers.map((n, index) => ({[n]: names[index]})))

console.log(a);
查看更多
时光不老,我们不散
3楼-- · 2020-01-31 01:38

var toObj = (ks, vs) => ks.reduce((o,k,i)=> {o[k] = vs[i]; return o;}, {});

var keys=['one', 'two', 'three'],
    values = [1, 2, 3];
var obj = toObj(keys, values);
console.log(obj);

查看更多
登录 后发表回答