2015-09-14 127 views
1

我試圖用下劃線找到數組中有一個具有一定條件的子對象。讓說,這是我的數組:下劃線查找嵌套對象

"array": [ 
    { 
    "user": { 
     "profileIcon": 913, 
     "id": 62019870 
    }, 
    "count": 1 
    }, 
    { 
    "user": { 
     "profileIcon": 770, 
     "id": 32558522 
    }, 
    "count": 2 
    } 
] 

現在我只想返回已USER.ID對象:62019870. 這是我到目前爲止的代碼,但它返回一個空數組:

var arr = _.filter(array, function(obj) { 
       return _.findWhere(obj.user, {id: 62019870}); 
      }); 

回答

3

findWhere函數在數組上,而不是在對象上。對於你的情況,你可以簡單地做

console.log(_.filter(array, function(obj) { 
    return obj.user.id === 62019870; 
})); 
// [ { user: { profileIcon: 913, id: 62019870 }, count: 1 } ] 

如果你的環境支持,原生Array.prototype.filter那麼你可以做同樣的,沒有下劃線,這樣

array.filter(function(obj) { 
    return obj.user.id === 62019870; 
}); 

如果你的環境支持ECMA Script 2015's Arrow functions,那麼你可以寫得相同,更簡潔,像這樣

array.filter(obj => obj.user.id === 62019870); 
+0

我會更喜歡@alexreardon的方式,如果我不需要擔心IE8它是'native'過濾器。 – Mritunjay

+0

@alexreardon謝謝,在答案中也包含了這個建議。 – thefourtheye