使用下划线.js过滤多维数组

Filtering through a multidimensional array using underscore.js

本文关键字:数组 过滤 js 下划线      更新时间:2023-09-26

我有一个名为 eventsevent 对象数组。每个event都有markets,一个包含market对象的数组。这里还有另一个数组叫做 outcomes ,包含outcome对象。

我想使用下划线.js或其他一些方法来查找所有具有市场的事件,这些事件具有名为 test 的属性的结果。

我想这将使用一系列过滤器来实现,但我没有太多运气!

我认为您可以使用下划线.js filtersome(又名"任何")方法来做到这一点:

// 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 ;
        });
    });
});

不需要下划线,你可以用本机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;
        });
    });
});

当然,您也可以使用相应的下划线方法(过滤/选择和任意/一些)。

试试这个:

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

演示

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);
});

以下是我将在不依赖库的情况下执行此操作的方法:

var matches = events.filter(function (event) {
  return event.markets.filter(function (market) {
    return market.outcomes.filter(function (outcome) {
      return outcome.hasOwnProperty('test');
    }).length;
  }).length;
});