convert array to object using lodash
11,879
Solution 1
Vanilla JS: A function that creates an object from an array:
function toObj(arr) {
return arr.reduce(function(p, c, i) {
p[names[i]] = c;
return p;
}, {});
}
Used with map
:
var out = arr.map(toObj);
Solution 2
You can use _.zipObject()
to zip up two arrays into an object. You are essentially mapping CSV data, with headers, to JavaScript objects.
You can try to search for JavaScript CSV converters. You may find some interesting results.
// Given names
var names = [ 'first', 'second', 'third', 'fourth' ];
// Array
var param = [ 1, 2, 3, 4 ];
// Becomes
var result = _.zipObject(names, param);
document.body.innerHTML = JSON.stringify(result, null, 2);
// Array of arrays
var param = [
[ 1, 2, 3, 4 ],
[ -4, 3, 1, 32 ],
];
// Becomes
var result = _.chain(param).map(function(p) {
return _.zipObject(names, p)
}).value();
document.body.innerHTML += '\n\n' + JSON.stringify(result, null, 2);
body {
font-family: monospace;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>
Author by
Klemensas
Updated on June 04, 2022Comments
-
Klemensas almost 2 years
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?