(If the order of the arguments looks strange, it's because I'm assuming [lodash/fp
module]
Here's the function that you want to execute on your argument:
f = _.compose(_.spread(_.zipObject),
_.unzip,
_.map(_.over(['size', 'no_of_ups'])));
And here it is in action:
arr = [{'size': '56 X 56 X 190', 'no_of_ups': 5}, {'size': '65 X 55 X 110', 'no_of_ups': 2}];
f = _.compose(_.spread(_.zipObject),
_.unzip,
_.map(_.over(['size', 'no_of_ups'])));
console.log(f(arr))
<script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)"></script>
And here's a bit of explanation:
_.map(_.over(['size', 'no_of_ups']))
runs _.over(['size', 'no_of_ups'])
on each element,
- and
_.over(['size', 'no_of_ups'])
simply picks 'size'
and the 'no_of_ups'
of the element and puts the two results in an array), so you get an array of arrays, in this case [["56 X 56 X 190", 5], ["65 X 55 X 110", 2]]
;
- then
_.unzip
fundamentally transposes the array of arrays, in this case giving you [["56 X 56 X 190", "65 X 55 X 110"], [5, 2]]
- finally
_.spread(_.zipObject)
feeds the two inner arrays as comma separated arguments to _.zipObject
, which constructs objects out of the two arrays, using them as the array of keys and the array of values, thus giving you the final result.
If you really want an array of objects rather than a single object, you can change _.zipObject
for _.zipWith((x,y) => ({[x]: y}))
.