lodash: mapping array to object
Another way with lodash 4.17.2
_.chain(params)
.keyBy('name')
.mapValues('input')
.value();
or
_.mapValues(_.keyBy(params, 'name'), 'input')
or with _.reduce
_.reduce(
params,
(acc, { name, input }) => ({ ...acc, [name]: input }),
{}
)
You should be using _.keyBy to easily convert an array to an object.
Docs here
Example usage below:
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
console.log(_.keyBy(params, 'name'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
If required, you can manipulate the array before using _.keyBy or the object after using _.keyBy to get the exact desired result.
Yep it is here, using _.reduce
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
_.reduce(params , function(obj,param) {
obj[param.name] = param.input
return obj;
}, {});
This seems like a job for Object.assign:
const output = Object.assign({}, ...params.map(p => ({[p.name]: p.input})));
Edited to wrap as a function similar to OP's, this would be:
const toHash = (array, keyName, valueName) =>
Object.assign({}, ...array.map(o => ({[o[keyName]]: o[valueName]})));
(Thanks to Ben Steward, good thinking...)