使用underscore.js过滤多维数组

8
我有一个名为“events”的event对象数组。每个event都有一个包含market对象的markets数组。 在这里面还有另一个名为outcomes的数组,其中包含outcome对象。
我想使用Underscore.js或其他方法查找所有具有包含属性名为“test”的outcomemarketevent
我想象中这将通过一系列过滤器实现,但我没有太大的运气!

有没有反向引用?我的意思是从“outcome”到“market”等等。因为在这种情况下,您可以过滤所有与搜索匹配的“outcome”对象,然后向后移动直到“event”,然后清理数组以获取唯一元素。 - fguillen
你能提供一个例子吗? - user1082754
4个回答

14

我认为你可以使用Underscore.js的filtersome(也称为“any”)方法来实现此目的:

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

我认为用户可能是指lodash.js,因为在underscore.js中我没有看到_.any方法。http://lodash.com/ - Fasani
1
@Fasani,这是Underscore而不是Lodash。_.any_.some的别名:http://underscorejs.org/#some - McGarnagle

3
不需要Underscore,你可以使用原生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任意/一些/有些/存在)。


0

试试这个:

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

演示


0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接