Merge keys array and values array into an object in JavaScript
As an alternate solution, not already mentioned I think :
var result = {};
keys.forEach((key, idx) => result[key] = values[idx]);
The simplest ES6 one-liner solution using Array reduce
:
const keys = ['height', 'width'];
const values = ['12px', '24px'];
const merged = keys.reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {});
use lodash.
_.zipObject
Example
_.zipObject(['a', 'b'], [1, 2]);
// ➜ { 'a': 1, 'b': 2 }
Simple JS function would be:
function toObject(names, values) {
var result = {};
for (var i = 0; i < names.length; i++)
result[names[i]] = values[i];
return result;
}
Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy :D