Filtering through a multidimensional array using underscore.js

后端 未结 4 1633
-上瘾入骨i
-上瘾入骨i 2021-01-12 05:58

I have an array of event objects called events. Each event has markets, an array containing market objects.

相关标签:
4条回答
  • 2021-01-12 06:13

    Try this:

    _.filter(events, function(me) { 
        return me.event && 
            me.event.market && me.event.market.outcome && 
            'test' in me.event.market.outcome
    }); 
    

    DEMO

    0 讨论(0)
  • 2021-01-12 06:14

    var events = [
      {
        id: 'a',
        markets: [{
          outcomes: [{
            test: 'yo'
          }]
        }]
      },
      {
        id: 'b',
        markets: [{
          outcomes: [{
            untest: 'yo'
          }]
        }]
      },
      {
        id: 'c',
        markets: [{
          outcomes: [{
            notest: 'yo'
          }]
        }]
      },
      {
        id: 'd',
        markets: [{
          outcomes: [{
            test: 'yo'
          }]
        }]
      }
    ];
    
    var matches = events.filter(function (event) {
      return event.markets.filter(function (market) {
        return market.outcomes.filter(function (outcome) {
          return outcome.hasOwnProperty('test');
        }).length;
      }).length;
    });
    
    matches.forEach(function (match) {
      document.writeln(match.id);
    });

    Here's how I would do it, without depending on a library:

    var matches = events.filter(function (event) {
      return event.markets.filter(function (market) {
        return market.outcomes.filter(function (outcome) {
          return outcome.hasOwnProperty('test');
        }).length;
      }).length;
    });
    
    0 讨论(0)
  • 2021-01-12 06:15

    No need for Underscore, you could do this with native JS.

    var events = [{markets:[{outcomes:[{test:x},...]},...]},...];
    return events.filter(function(event) {
        return event.markets.some(function(market) {
            return market.outcomes.some(function(outcome) {
                return "test" in outcome;
            });
        });
    });
    

    Yet of course you could also use the corresponding underscore methods (filter/select and any/some).

    0 讨论(0)
  • 2021-01-12 06:34

    I think you can do this using the Underscore.js filter and some (aka "any") methods:

    // 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 ;
            });
        });
    });
    
    0 讨论(0)
提交回复
热议问题