2014-02-07 40 views
1

我有類似如下的數組:過濾器由物業兒童陣列使用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 = 1和dId = 11的細節,並且做出ah-性質的總和。所以例如。濾波ID = 1和DID = 11應該返回3.

我想是這樣的:_.where(result, {id: 1, details.dId:11})

但我無法得到它的工作。

我創建了一個小提琴: http://jsfiddle.net/j9Htk/

任何幫助表示讚賞

感謝

托馬斯

回答

3

首先過濾res ULTS讓那些具有匹配的ID(能夠處理更多的一個具有相同ID):

var filteredList = _.filter(result, function(value){ 
    return value.id == 1; 
}); 

現在總結所有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); 
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); 
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() 
}