I have an array like the following:
var result=[{"id": 1, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}, {"ah": 2.0, "dId": 12}]}, {"id": 2, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}]}]
Now I would like to filter it by the Id and dId-properties using underscore.js, eg. giving me all details for id=1 and dId=11 and doing a sum of the ah-properties. So eg. filtering for id=1 and dId=11 should return 3.
I tried something like this: _.where(result, {id: 1, details.dId:11})
But I couldn't get it to work.
I created a fiddle: http://jsfiddle.net/j9Htk/
Any help is appreciated
thanks
Thomas
First filter the results to get those that have a matching id (can handle more the one with the same id):
var filteredList = _.filter(result, function(value){
return value.id == 1;
});
Now sum the sums of all the ahs:
var sum = _.reduce(filteredList , function(memo, value){
// find all details that have a matching dId
var details = _.filter(value.details, function(detail){ return detail.dId == 11; });
// return the sum of all the found details
return memo + _.reduce(details, function(memo2, detail){ return memo2 + detail.ah; }, 0);
}, 0);
I'm a beginner at underscore, here's my try:
var result=[{"id": 1, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}, {"ah": 2.0, "dId": 12}]}, {"id": 2, "details": [{"ah": 1.0, "dId": 11},{"ah": 2.0, "dId": 11}]}];
function calculate( result, id, dId ){
var sum = 0;
_.each( result[id].details, function( detail ){
if( detail.dId == dId ){
sum += detail.ah;
}
});
console.log( 'id: ' + id + ' sum: ' + sum );
}
calculate( result,1,11 );
function extractSumOfAhs(result, id, dId) {
return _.reduce(
_.pluck(
_.where(
_.flatten(
_.pluck(
_.where(
result,
{ id: id }
),
"details"
)
),
{dId: dId}
),
"ah"
),
function(a,b) { return a + b; }
)
}
or with chain:
function extractSumOfAhs(result, id, dId) {
return _.chain(result)
.where({id : id})
.pluck("details")
.flatten()
.where({dId : dId})
.pluck("ah")
.reduce(function(a, b) { return a + b;})
.value()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.