I have the following object:
data = [
{ name: 'foo', type: 'fizz', val: 9 },
{ name: 'foo', type: 'buzz', val: 3 },
{ name: 'bar', type: 'fizz', val: 4 },
{ name: 'bar', type: 'buzz', val: 7 },
];
And used lodash map:
result = _.map(data, function item, idx){
return {
key: item[key],
values: item.value,
}
}
Which results in:
[
{ key: foo, val: 9 },
{ key: foo, val: 3 },
{ key: bar, val: 4 },
{ key: bar, val: 7 },
]
but now I'm trying to return:
[
{ key: 'foo', val: 12 },
{ key: 'bar', val: 11 },
]
I tried using reduce which seems to only output to a single object, which I could then convert back into an array, but I feel like there must be an elegant way to use lodash to go from my source data straight to my desired result without all of the intermediate steps.
I thought this was addressing my exact problem, but it seems like quite a bit of work just to have to convert the object into the desired array of objects outlined above.
Cheers.
The array reduce in JavaScript is a predefined method used to reduce an array to a single value by passing a callback function on each element of the array. It accepts a function executed on all the items of the specified array in the left-to-right sequence. The returned single value is stored in the accumulator.
reduce can use initial and return values of any type, which makes it very flexible. Let's explore how we can use it to perform some common tasks with plain objects.
Using the reduce method. The reduce() method executes a reducer function (a function that you provide as an argument) on each element of the array, resulting in a single output value. Here, the reducer function provided is concat() and the result is stored in an empty array.
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
A twist to the accepted answer that uses groupBy instead of reduce to do the initial grouping:
var result = _.chain(data)
.groupBy('name')
.map((group, key) => ({ key, val : _.sumBy(group, 'val') }))
.value();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With