Filtering through a multidimensional array using underscore.js

后端 未结 4 1682
-上瘾入骨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: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;
    });
    

提交回复
热议问题