1

I have the following events array. For every event there is a hash as {organisation name: [{participant 1}, {participant 2}, {...}]}

"events": [
    {
        "Org A": [
            {
                "event_id": 1,
                "id": 432,
                "name": "John Doe",
                "role": null
            },
            {
                "event_id": 1,
                "id": 312,
                "name": "Jane Mow",
                "role": [
                  "speaker"
                ]
            }
        ],
    }
],

I would like to filter this events array to only contain participants whose role contains speaker. Also, when there are no speakers in the participant array, the respective organisation entry needs to be removed from the Hash (object).

To filter the array of objects, I tried using this:

_.each(events, function(event){
  _.filter(event, function(p) { 
   _.filter(p, function(d){ 
     return _.some(d.role, function(r){ 
      return r == "speaker"}) 
    }) 
  }) 
})   

This however doesn't work.

4
  • 1
    d.role is an array and therefore r == speaker will never be true Commented Oct 22, 2015 at 9:45
  • your first _.filter has no return Commented Oct 22, 2015 at 9:49
  • filter does return a new array, but you're not doing anything with it. Commented Oct 22, 2015 at 9:49
  • _.some checks against each element of an array so why shouldn't d.role be an array? Commented Oct 22, 2015 at 9:50

1 Answer 1

1

Try this

var data = {
    "events": [{
        "Org A": [{
            "event_id": 1,
            "id": 432,
            "name": "John Doe",
            "role": null
        }, {
            "event_id": 1,
            "id": 312,
            "name": "Jane Mow",
            "role": [
                "speaker"
            ]
        }],
        
        "Org B": [],
        "Org C": []
    }]
};

var SPEAKER = 'speaker';

var result = _.map(data.events, function (events) {
  return _.chain(events)
    .mapObject(function (value, key) {
      return _.filter(value, function (event) {
        return _.isArray(event.role) && _.indexOf(event.role, SPEAKER) >= 0; 
      });
    })
    .pick(function (value) {
      return value && value.length;
    })
    .value();
})

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.