![](/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.