简体   繁体   English

lodash过滤掉具有空值的对象

[英]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. 但是,如果classes数组至少有一个没有null位置的对象,那么应该返回它。 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_.every的组合:

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

https://jsfiddle.net/W4QfJ/1534/ 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/ https://jsfiddle.net/oobxt82n/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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