2016-03-08 115 views
0

排除我有一個Array a問題lodash:陣列濾波器和對象

[ 
    {id: 1,name: "Question 1"}, 
    {id: 2,name: "Question 2"}, 
    {id: 3,name: "Question 3"}, 
] 

一個Array b問答,其屬性question_id引用idArray a的屬性:

​​

用lodash,我想過濾Array a排除所有的個答案被引用到它,期望輸出:

[ 
    {id: 1,name: "Question 1"}, 
    {id: 3,name: "Question 3"}, 
] 

回答

1
var questions = [ 
    {id: 1,name: "Question 1"}, 
    {id: 2,name: "Question 2"}, 
    {id: 3,name: "Question 3"}, 
]; 

var answers = [ 
    {id: 1, question_id: 2,name: "My Answer to Question 2"} 
]; 

var filtered = _.filter(questions, isNotReferencedByAnyAnswer); 

function isNotReferencedByAnyAnswer(question) { 
    return _.findIndex(answers, {'question_id': question.id}) === -1; 
} 
+0

非常酷PRASHANT,謝謝。 – TMichel

+0

不客氣。僅供參考,這可以通過香草JS只有現在一天來實現。所以,如果你只是爲了這個加載Lodash,那麼最好只用香草JS。 – Prashant