2016-11-23 69 views
0

我有學校收藏,學校有老師收藏,每個老師都有學生收藏。每個學生都有全球studentUniqueId。用lodash查詢複雜對象

我想通過使用lodash找到有學生的學校,其中studentUniqueId是:「Abc123946」。可以在循環內完成,但我想像我們在linq中那樣優雅地完成它。

的樣本數據是在這裏:

https://jsfiddle.net/94f4wvb6/

[ 
    { 
    "schoolId":1, 
    "schoolName":"school name 1", 
    "teachers":[ 
    { 
     "name":"Teacher Name 1", 
     "subject":"Math", 
     "students":[ 
      { 
       "studentUniqueId":"Abc123940", 
       "name":"Student Name 1" 
      }, 
      { 
       "studentUniqueId":"Abc123941", 
       "name":"Student Name 1" 
      } 
     ] 
    }, 
    { 
     "name":"Teacher Name 2", 
     "subject":"English", 
     "students":[ 
      { 
       "studentUniqueId":"Abc123942", 
       "name":"Student Name 1" 
      }, 
      { 
       "studentUniqueId":"Abc123943", 
       "name":"Student Name 1" 
      } 
     ] 
    } 
    ] 
}, 
{ 
"schoolId":2, 
    "schoolName":"school name 2", 
    "teachers":[ 
    { 
     "name":"Teacher Name 3", 
     "subject":"Math", 
     "students":[ 
      { 
       "studentUniqueId":"Abc123944", 
       "name":"Student Name 7" 
      }, 
      { 
       "studentUniqueId":"Abc123945", 
       "name":"Student Name 8" 
      } 
     ] 
    }, 
    { 
     "name":"Teacher Name 4", 
     "subject":"English", 
     "students":[ 
      { 
       "studentUniqueId":"Abc123946", 
       "name":"Student Name 5" 
      }, 
      { 
       "studentUniqueId":"Abc123947", 
       "name":"Student Name 6" 
      } 
     ] 
    } 
    ] 
} 
] 

回答

1

下面是使用findsome做的一種方式:

let theOneThatIWant = "Abc123942"; 

let school = _.find(schools, function(school){ 
    return _.some(school.teachers, function(teacher){ 
     return _.some(teacher.students, {studentUniqueId: theOneThatIWant}); 
    }) 
}) 
1
_.find(schools, function(school) { 
    return _.chain(school.teachers) 
     .map('students') 
     .flatten() 
     .map('studentUniqueId') 
     .includes('Abc123946') 
     .value(); 
}) 
+0

外型優雅,但它說,鏈不一個函數。可能它存在於以前版本的lodash之一中? – londondev

+0

@londondev使用這個構建https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js – stasovlas