我有一个event名为的对象数组events.每个event都有markets一个包含market对象的数组.在这里有另一个叫做outcomes包含outcome对象的数组.
在这个问题中,我要求[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";
});
});
});
Run Code Online (Sandbox Code Playgroud)
这很有效,但我想知道如果我想过滤每个市场的结果,我将如何改变它,以便market.outcomes只存储等于的结果bar.目前,这只是给我市场的结果具有一些固定的test属性.我想剥掉那些没有的东西.
使用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
}
Run Code Online (Sandbox Code Playgroud)
此代码将删除所有没有test属性的结果,所有空市场和events阵列中的所有空事件.
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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23283 次 |
| 最近记录: |