簡體   English   中英

Underscore.js .filter()和.any()

[英]Underscore.js .filter() and .any()

我有一個稱為eventsevent對象數組。 每個event都有markets ,一個包含market對象的數組。 在此內部,還有另一個數組稱為outcomes ,包含outcome對象。

這個問題中 ,我要求一種[Underscore.js]方法來查找所有具有市場結果的事件,這些事件的結果具有名為test的屬性。 答案是:

// filter where condition is true
_.filter(events, function(evt) {

    // return true where condition is true for any market
    return _.any(evt.markets, function(mkt) {

        // return true where any outcome has a "test" property defined
        return _.any(mkt.outcomes, function(outc) {
            return outc.test !== "undefined" && outc.test !== "bar";
        });
    });
});

這很好用,但是我想知道如果要過濾每個市場的結果如何改變它,以便market.outcomes僅存儲等於bar 目前,這只是給我帶來了具有某些 test屬性的結果的市場。 我想剔除那些沒有的。

使用splice方法刪除數組,使其成為一個簡單的循環:

var events = [{markets:[{outcomes:[{test:x},...]},...]},...];
for (var i=0; i<events.length; i++) {
    var mrks = events[i].markets;
    for (var j=0; j<mrks.length; j++) {
        var otcs = mrks[j].outcomes;
        for (var k=0; k<otcs.length; k++) {
            if (! ("test" in otcs[k]))
                 otcs.splice(k--, 1); // remove the outcome from the array
        }
        if (otcs.length == 0)
            mrks.splice(j--, 1); // remove the market from the array
    }
    if (mrks.length == 0)
        events.splice(i--, 1); // remove the event from the array
}

此代碼將從events數組中刪除所有沒有test屬性的結果,所有空白的市場和所有空白的events

下划線版本可能如下所示:

events = _.filter(events, function(evt) {
    evt.markets = _.filter(evt.markets, function(mkt) {
        mkt.outcomes = _.filter(mkt.outcomes, function(otc) {
            return "test" in otc;
        });
        return mkt.outcomes.length > 0;
    });
    return evt.markets.length > 0;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM