2016-03-20 17 views
3

Bir kurs nesnesine sahibim ve sınıflar dizisinin boş bir konumuna sahip olup olmadığını kontrol ederek filtrelemek istiyorum. Ancak, sınıflar dizisi, boş bir konuma sahip olmayan en az bir nesneye sahipse, o zaman döndürülmelidir. İşte üzerinde çalışıyorum bir örnek nesne:lodash null değeriyle nesneleri filtrele

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", 
     }], 
    } 
] 

ve burada almak için beklemek sonucudur:

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", 
     }], 
    } 
] 

Sadece aklım bu nedeniyle filtrelemek için nasıl sarılı alamayan nesnelerin iç içe geçmiş yapısı. Herhangi bir yardım büyük memnuniyetle karşılanacaktır!

cevap

1

Nasıl:

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/

+0

Bu sadece bir şehir döndürür: 'Paris', ama aynı zamanda şehirdeki bir sınıfla ders nesnesini de geri göndermelidir: 'Montreal'. – Alistair

+0

@Alistair Oh, critera'yı biraz yanlış okudu. – Johan

+0

olmasına rağmen kolayca değiştirilir. Şimdi çalışıyor :) – Alistair