Home > Net >  Filter nested array of objects base on another array
Filter nested array of objects base on another array

Time:03-07

let students = [{name:'Sam', subjects: [{name:'math',code:'123'},{name:'english, code:'321'}, {name: 'Tom', subjects: [{name:'math', code:'123'}]}, {name: 'Joe', subjects:[{name: 'english, code:'321'}]}]

let subject = ['english']

expectedOutput = [{name: 'Joe', subjects:[{name: 'english, code:'321'}]}]

CodePudding user response:

expectedOutput = students.filter((student) => {
   student.subjects.some((student_subject) => subject.includes(student_subject.name))
})

Since you haven't explained what you're trying to achieve and what you tried (providing actual code), I hope this is what you needs. If the student must match exactly the "subject" variable (meaning, in your case, he must have english subject and ONLY english subject) then it's a bit different and you should read @jsN00b comment under my answer

  • Related