[英]Filtering through a multidimensional array using underscore.js
I have an array of event
objects called events
. 我有一个名为
events
的event
对象数组。 Each event
has markets
, an array containing market
objects. 每个
event
都有markets
,一个包含market
对象的数组。 Inside here there is another array called outcomes
, containing outcome
objects. 这里面还有另外一个数组叫
outcomes
,包含outcome
的对象。
I want to use Underscore.js or some other method to find all of the events which have markets which have outcomes which have a property named test
. 我想使用Underscore.js或其他方法来查找具有市场的所有事件,这些市场的结果具有名为
test
的属性。
I imagine this would be achieved using a series of filters but I didn't have much luck! 我想这可以通过一系列过滤器实现,但我没有太多运气!
I think you can do this using the Underscore.js filter
and some
(aka "any") methods: 我认为你可以使用Underscore.js
filter
和some
(也就是“任何”)方法来做到这一点:
// 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 ;
});
});
});
No need for Underscore, you could do this with native JS. 不需要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;
});
});
});
Yet of course you could also use the corresponding underscore methods ( filter/select and any/some ). 当然,你也可以使用相应的下划线方法( filter / select和any / some )。
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.