![](/img/trans.png)
[英]Using Underscore.js to filter an array of objects on a property using a 'contains'
[英]filter by property in child array using underscore.js
我有一个如下数组:
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/
任何帮助表示赞赏
谢谢
托马斯
首先过滤结果以获得具有匹配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);
我是下划线的初学者,这是我的尝试:
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; }
)
}
或链:
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.