简体   繁体   English

lodash:数组过滤器,按对象排除

[英]lodash: array filter and exclude by object

I have an Array a of Questions : 我有一个问题 Array a

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

and an Array b of Answers , where the property question_id references the property id of Array a : 和一个Answers Array b ,其中属性question_id引用Array a的属性id

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

With lodash, I want to filter Array a to exlude all the Answers that are referencing to it, expecting the output: 使用lodash,我想过滤Array a以排除所有引用它的答案 ,并期望输出:

[
  {id: 1,name: "Question 1"},
  {id: 3,name: "Question 3"},
]
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;
}

A short answer with lodash.differenceWith 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' } ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM