2013-09-21 155 views
0

我已經拉出我的頭髮與此一 - 我有以下陣列,持續的對象 - 它包含一個憑證陣列(包含對象的可能的無限數量)Underscore.js陣列過濾

var retailer = [ { _id: 52000c, 
    address: 'bla bla bla', 
    email: '[email protected]', 
    img: 'http://bla.jpg', 
    intro: ' hello', 
    strapLine: 'goodbye', 
    tel: '0000 0000000', 
    title: 'YE OLDE SHOPPE', 
    website: 'http://', 
    vouchers: 
    [ { _id: 523d003, 
     barcode: false, 
     description: 'blah', 
     endTime: '20 December 2013', 
     hidden: true, 
     redemptionCode: 'redemptionCode', 
     smallPrint: 'blah.', 
     startTime: 'Today', 
     title: 'blahbla' }, 
     { _id: 523de3, 
     barcode: false, 
     description: 'blah', 
     endTime: '20 December 2013', 
     hidden: true, 
     redemptionCode: 'redemptionCode', 
     smallPrint: 'blah.', 
     startTime: 'Today', 
     title: 'blahbla' }, 
     { _id: 523dr, 
     barcode: false, 
     description: 'blah', 
     endTime: '20 December 2013', 
     hidden: false, 
     redemptionCode: 'redemptionCode', 
     smallPrint: 'blah.', 
     startTime: 'Today', 
     title: 'blahbla' } ] 
} ] 

使用underscore.js,我試圖用隱藏的屬性(hidden == true)過濾掉那些憑證對象 - 所以我最終得到了以下內容,這樣我只能得到可見的憑證(隱藏==假)

var retailer = [ { _id: 52000c, 
     address: 'bla bla bla', 
     email: '[email protected]', 
     img: 'http://bla.jpg', 
     intro: ' hello', 
     strapLine: 'goodbye', 
     tel: '0000 0000000', 
     title: 'YE OLDE SHOPPE', 
     website: 'http://', 
     vouchers: 
     [{ _id: 523dr, 
      barcode: false, 
      description: 'blah', 
      endTime: '20 December 2013', 
      hidden: false, 
      redemptionCode: 'redemptionCode', 
      smallPrint: 'blah.', 
      startTime: 'Today', 
      title: 'blahbla' }] 
    } ] 

所以使用下劃線js,我寫了下面的ba sed的在以前堆棧溢出線程(Filtering array with underscore.js

var visibleVouchers = _(retailer[0].vouchers).filter(function (x) { return !x.hidden;}); 

而這將返回所有可見的憑證 - 但是,我失去了零售商的過程中。什麼是最好的方法來做到這一點?我已經嘗試了很多不同的東西 - 例如,試圖用新的替代舊的voucheers陣列 - 但它似乎並不奏效。

謝謝, 羅布

回答

2

使用_.map()零售商,這是一個一對一的映射。在回調(每個零售商物品)內部,使用_.filter()(或_.reject(),根據您的感覺)過濾出憑證。

var arrRetailers = _.map(retailers, function(retailer) { 
    var item = _.extend({}, retailer); 
    item.vouchers = _.filter(retailer.vouchers, function(voucher) { 
    return !voucher.hidden; 
    }) || []; //in case of there is no "visible" voucher 
    return item; 
}); 

這將返回一個新數組,並且不會更改您的初始零售商數組。

如果你喜歡_.reject(),你的回調必須進行相應的調整:

_.reject(retailer.vouchers, function(voucher) { 
    return voucher.hidden; //note there is no exclamation mark 
}) || []; 

希望這有助於!

+1

真棒 - 所以這保留了原產地,並創造了一個新的我需要的一切。謝謝 :) – Rob

0

我發現了一篇博文http://www.untitleddesigns.com/2011/javascript-replace-array-contents/,它似乎回答了我的問題 - 它確實有效,儘管我不熟悉原型 - 所以不太清楚其工作原因。

var visibleVouchers = _(retailer[0].vouchers).filter(function (x) { return !x.hidden;}); 
retailer[0].vouchers.length = 0; 
Array.prototype.push.apply(retailer[0].vouchers, visibleVouchers);