Kingsley
Kingsley

Reputation: 365

Getting an object out of an array in javascript

I have an array of objects (student objects which have properties like studentID, grade, dob, registeredDate) and I have another array of objects (books objects which have properties studentID, bookID, bookISBN).

It's a Web app for managing the library at a small school. What I want to do is that when a book (say has title Welcome Home) has been borrowed by student with studentID 4, when you try to lend that book (of course a copy since the library can have a number of them in stock) to someone else, the student with studentID 4 shouldn't be available in the list of students who are eligible to get that book (unless if the student had returned the book first).

The booksList Array is like below:

[
{
bookEdition: "2nd edition",
bookISBN: 9876533278765,
bookStatus: 0,
bookTitle: "Real Machines",
dateTaken: "2018-10-28",
returnDate: "2018-11-27",
studentID: "0000003"
},

{
bookEdition: "2015 edition",
bookISBN: 9876532226712,
bookStatus: 0,
bookTitle: "Real Machines",
dateTaken: "2018-08-28",
returnDate: "2018-09-27",
studentID: "0000004"
}
];

The studentsList is as below:

[
{
bio: "Needs extra work. Has problems with mathematics",
birthday: "2005-05-12",
className: "grade 5",
fullname: "Bridget Friday",
gender: "Female",
parentName: "Josam Friday",
studentID: "0000003",
studentStatus: "approved"
}, 

{
bio: "A bit naughty but intelligent. Pay close attention to his diet.",
birthday: "2003-11-07",
className: "grade 6",
fullname: "Charles Ben",
gender: "Male",
parentName: "Chris Ben",
studentID: "0000004",
studentStatus: "approved"
}
];

Now, I was trying to use the filter function but it doesn't give me the results I want. The thing that links the two array objects and the objects in them is the studentID.

I tried

var legitStudents = studentsList.filter(el => {
  return !booksList.includes(el.studentID);
});

The above doesn't work. The arrays (studentList and booksList) are fetched dynamically and I can't tell which studentIDs are in booksList.

How can I get this to work as I want them?

Upvotes: 0

Views: 1484

Answers (2)

Sajal Preet Singh
Sajal Preet Singh

Reputation: 379

You can use Rocky Sims' solution or you can try this as well

var legitStudents = studentList.filter(student => {
  return !booksList.filter(book => book.studentID === student.studentID).length;
});

Upvotes: 1

Rocky Sims
Rocky Sims

Reputation: 3598

return !booksList.includes(el.studentID);

should be

return !booksList.map(i => i.studentID).includes(el.studentID);

As a couple people said in the comments of your question, the problem is your code is expecting booksList to be an array of studentIDs. Since it's actually a list of books that have been checked out by students, you first need to make an array of all studentIDs in booksList then you can use includes on the resulting array. See map.

Upvotes: 1

Related Questions