简体   繁体   中英

lodash filter out objects with null value

I have a courses object and I want to filter it by checking if it's classes array has a null location or not. However, if the classes array has at least one object that doesn't have a null location then it should be returned. Here's an example object that I'm working on:

    courses: [
    {
        title: "Introduction to English 101",
        classes: [{
            location: null,
            endDate: "2016-03-25T22:00:00.000Z",
            startDate: "2016-03-23T22:00:00.000Z",
        }]
    },
    {
        title: "Introduction to Japanese 101",
        classes: [{
            location: {
                city: "Paris",
            },
            endDate: "2016-03-25T22:00:00.000Z",
            startDate: "2016-03-23T22:00:00.000Z",
        }]
    }, 
    {
        title: "Introduction to Spanish 101",
        classes: [{
            location: null,
            startDate: "2016-02-23T10:11:35.786Z",
            endDate: "2016-02-23T12:11:35.786Z",
        }, 
        {
            location: {
                city: "Montreal",
            },            
            startDate: "2016-04-01T10:11:35.786Z",
            endDate: "2016-04-15T10:11:35.786Z",
        }],
    }
]

and here's the result I expect to get:

    courses: [
    {
        title: "Introduction to Japanese 101",
        classes: [{
            location: {
                city: "Paris",
            },
            endDate: "2016-03-25T22:00:00.000Z",
            startDate: "2016-03-23T22:00:00.000Z",
        }]
    }, 
    {
        title: "Introduction to Spanish 101",
        classes: [{
            location: null,
            startDate: "2016-02-23T10:11:35.786Z",
            endDate: "2016-02-23T12:11:35.786Z",
        }, 
        {
            location: {
                city: "Montreal",
            },            
            startDate: "2016-04-01T10:11:35.786Z",
            endDate: "2016-04-15T10:11:35.786Z",
        }],
    }
]

I just can't get my mind wrapped around how to filter this due to the nested structure of the objects. Any help would be greatly appreciated!

How about using a combination of _.filter and _.every like:

_.filter(obj.courses, function(o) {
  return !_.every(o.classes,{ location: null });
});

https://jsfiddle.net/W4QfJ/1534/

How about this:

var data = { courses: [/* your sample data above */] };

var result = data.courses.filter(function(course){  
    return course.classes && course.classes.some(function(course){
       return course && course.location !== null;
   });
});

https://jsfiddle.net/oobxt82n/

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