简体   繁体   中英

Filtering nested array of objects

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM