lodash:数组过滤并按对象排除

时间:2016-03-08 17:30:55

标签: javascript lodash

我有{{1>}个问题

Array a

以及答案[ {id: 1,name: "Question 1"}, {id: 2,name: "Question 2"}, {id: 3,name: "Question 3"}, ] ,其中属性Array b引用question_id的属性id

Array a

使用lodash,我想过滤[ {id: 1, question_id: 2,name: "My Answer to Question 2"} ] 以排除引用它的所有 Answers ,期望输出:

Array a

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

lodash.differenceWith

的简短回答
arr = [
       {id: 1,name: "Question 1"},
       {id: 2,name: "Question 2"},
       {id: 3,name: "Question 3"},
]
arr1 = [
  {id: 1, question_id: 2,name: "My Answer to Question 2"}
]
_.differenceWith(arr, arr1, (arrVal, othVal) => arrVal.id === othVal.question_id)

// result

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