Reputation: 2543
I have the following object:
{key: [{thing: value, stuff: value}, {thing: value, stuff: value}], key2: [{thing: value, stuff: value}, {thing: value, stuff: value}]}
For each key, I'd like to get either an array of only stuff values for each key or better yet a sum of stuff values for each key. Stuff values are numbers that I want to sum. I've been at this all day and am at my wits end.
Here is the exact form of the data:
Top Level:
[Array[1], Array[1], Array[3], Array[1], Array[1], Array[1], Array[2], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1], Array[1]]
Here is Array[3]:
2: Array[3]
The first object in Array[3]:
0: Object
The contents of the object:
Amounts: Array[3]
Avg: 1202.38
Bill: 871.43
There are another dozen key value pairs in each object. I want to sum all of the "Bill" for each Array which is grouped by user already. Bill exists within each object within each array.
To get the version you see at the very top I did:
_.groupBy(_.flatten(BigArray),'Name');
I thought this would be a move in the right direction as it makes explicit who the user is since I need the total bill for each Name.
Upvotes: 1
Views: 1129
Reputation: 38131
Is this what you were after?
var d = {
key: [{
thing: "a",
stuff: 1
}, {
thing: "b",
stuff: 2
}],
key2: [{
thing: "a",
stuff: 3
}, {
thing: "b",
stuff: 4
}]
};
var result = _.map(d, function(arr, key) {
var stuffValues = _.pluck(arr, 'stuff');
return {
key: key,
stuffSum: _.reduce(stuffValues, function(memo, num) {
return memo + +num;
}, 0)
};
});
document.getElementById('output').textContent = JSON.stringify(result);
// => [{"key":"key","stuffSum":3},{"key":"key2","stuffSum":7}]
<script src="//underscorejs.org/underscore-min.js"></script>
<pre id="output"></pre>
Upvotes: 1