我有一个如下数组:
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}]}]
现在我想使用underscore.js通过Id和dId属性过滤它,例如。给我id = 1和dId = 11的所有细节,并做了一个ah属性的总和。所以,例如。过滤id = 1和dId = 11应返回3.
我尝试过这样的事情:_.where(result, {id: 1, details.dId:11})
但我无法让它发挥作用。
我创造了一个小提琴: http://jsfiddle.net/j9Htk/
感谢任何帮助
感谢
托马斯
答案 0 :(得分:3)
首先过滤结果以获得具有匹配id的那些(可以处理具有相同id的那个):
var filteredList = _.filter(result, function(value){
return value.id == 1;
});
现在总结所有的啊:
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);
答案 1 :(得分:0)
我是下划线的初学者,这是我的尝试:
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 );
答案 2 :(得分:0)
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; }
)
}
或与链:
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()
}