I need to convert an array or an array of arrays to an object with keys named from an array of names. Example:
//given names
names = ['first', 'second', 'third', 'fourth']
//array
param = [1, 2, 3, 4]
//becomes
result = {first: 1, second: 2, third: 3, fourth: 4}
//array of arrays
param = [
[1, 2, 3, 4],
[-4, 3, 1, 32],
]
//becomes
result = [
{first: 1, second: 2, third: 3, fourth: 4},
{first: -4, second: 3, third: 1, fourth: 32},
]
My current solution is this:
var names = ['first', 'second', 'third', 'forth'];
function arrayToObject(array, names) {
var result = {};
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'object') {
result[i] = arrayToObject(array[i], names);
continue;
}
result[names[i]] = array[i];
}
return result;
}
The problem with this solution is that it always returns an object, though it should return an array of objects when I pass in an array of arrays. Is there a way to do this with lodash and I'm not seeing it?
_.zipObject()is concise.