使用下划线.js过滤多维数组
Filtering through a multidimensional array using underscore.js
我有一个名为 events
的 event
对象数组。每个event
都有markets
,一个包含market
对象的数组。这里还有另一个数组叫做 outcomes
,包含outcome
对象。
我想使用下划线.js或其他一些方法来查找所有具有市场的事件,这些事件具有名为 test
的属性的结果。
我想这将使用一系列过滤器来实现,但我没有太多运气!
我认为您可以使用下划线.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 ;
});
});
});
不需要下划线,你可以用本机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;
});
相关文章:
- 使用一个键的值数组过滤多个javascript对象
- 根据另一个包含角度 js 中对象的数组过滤包含对象的数组
- Javascript:按字符串数组过滤对象数组
- 在 javascript 中使用数组过滤 for AngularJS
- 挖空和选择器的数组过滤问题
- Lodash 按数组的属性数组过滤
- 如何用另一个字符串数组过滤ng重复中的字符串数组
- 如何根据javascript数组过滤rss数据
- 基于NodeJS中的其他数组过滤/搜索对象的JavaScript数组
- 使用不带嵌套循环的数组过滤对象数组js
- 使用数组过滤数组Javascript
- 用一维数组过滤多维数组
- AngularJS:如何给值数组过滤
- Angularjs,逐个数组过滤
- 用另一个对象数组过滤Javascript对象数组
- 创建搜索栏以将数组过滤到表中
- 通过id数组过滤角度数据
- coffeescript -数组过滤不工作
- Backbone.js:如何通过模型ID数组过滤对象集合
- 使用基于嵌套值的数组过滤对象数组