Filtering through a multidimensional array using underscore.js

I have an array of event objects called events . Each event has markets , an array containing market objects. Inside there is another array called outcomes containing outcome objects.

I want to use Underscore.js or some other method to find all events that have markets that have results that have a property called test .

I guess this will be achieved with a series of filters, but I was out of luck!

+8
javascript object arrays
source share
4 answers

I think you can do this using the Underscore.js filter and some (so-called "any") methods:

 // 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 ; }); }); }); 
+12
source share

No need for Underscore, you can do it with the built-in 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; }); }); }); 

However, you can also use the appropriate underscore methods ( filter / select and any / some ).

+3
source share

Try the following:

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

Demo

0
source share

 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 is how I would do it, regardless of the 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; }); 
0
source share

All Articles