Javascript Underscore.js .filter() 和 .any()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10824091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Underscore.js .filter() and .any()
提问by
I have an array of event
objects called events
. Each event
has markets
, an array containing market
objects. Inside here there is another array called outcomes
, containing outcome
objects.
我有一个event
名为events
. 每个event
都有markets
,一个包含market
对象的数组。里面还有另一个数组叫做outcomes
,包含outcome
对象。
In this question, I asked for a [Underscore.js] way to find all of the events which have markets which have outcomes which have a property named test
. The answer was:
在这个问题中,我要求使用 [Underscore.js] 方法来查找所有具有名为test
. 答案是:
// 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" && outc.test !== "bar";
});
});
});
This works great, but I'm wondering how I would alter it if I wanted to filter the outcomes for each market, so that market.outcomes
only stored outcomes that were equal to bar
. Currently, this is just giving me markets which have outcomes which have someset test
properties. I want to strip out the ones that do not.
这很好用,但我想知道如果我想过滤每个市场的结果,我将如何改变它,以便market.outcomes
只存储等于bar
. 目前,这只是给了我具有某些设定test
属性的结果的市场。我想去掉那些没有的。
回答by Bergi
Make it a simple loop, using the splice methodfor the array removals:
使用splice 方法删除数组,使其成为一个简单的循环:
var events = [{markets:[{outcomes:[{test:x},...]},...]},...];
for (var i=0; i<events.length; i++) {
var mrks = events[i].markets;
for (var j=0; j<mrks.length; j++) {
var otcs = mrks[j].outcomes;
for (var k=0; k<otcs.length; k++) {
if (! ("test" in otcs[k]))
otcs.splice(k--, 1); // remove the outcome from the array
}
if (otcs.length == 0)
mrks.splice(j--, 1); // remove the market from the array
}
if (mrks.length == 0)
events.splice(i--, 1); // remove the event from the array
}
This code will remove all outcomes that have no test
property, all empty markets and all empty events from the events
array.
此代码将从数组中删除所有没有test
属性的结果、所有空市场和所有空事件events
。
An Underscore version might look like that:
Underscore 版本可能如下所示:
events = _.filter(events, function(evt) {
evt.markets = _.filter(evt.markets, function(mkt) {
mkt.outcomes = _.filter(mkt.outcomes, function(otc) {
return "test" in otc;
});
return mkt.outcomes.length > 0;
});
return evt.markets.length > 0;
});