繁体   English   中英

在JavaScript中从数组中获取对象

[英]Getting an object out of an array in javascript

我有一个对象数组(具有属性如studentIDgradedobregisteredDate学生对象),还有另一个对象数组(具有属性studentIDbookIDbookISBN books对象)。

这是一个用于管理小型学校图书馆的Web应用程序。 我想做的是,当学生studentID 4的学生借用了一本书(例如标题为Welcome Home )时,当您尝试借书时(当然是一本副本,因为图书馆有很多库存)对于其他人,具有学生studentID 4的学生不应出现在有资格获得该书的学生列表中(除非该学生首先退还该书)。

booksList数组如下所示:

[
{
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"
}
];

学生名单如下:

[
{
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"
}
];

现在,我正在尝试使用过滤器功能,但没有给我想要的结果。 链接两个数组对象及其中的对象的对象是studentID

我试过了

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

上面的方法不起作用。 阵列( studentListbooksList )被动态地提取和我不能告诉哪个studentID s为在booksList

我怎样才能使其按需运行?

return !booksList.includes(el.studentID);

应该

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

就像一对人在对您的问题的评论中所说的那样,问题是您的代码期望booksList是一个studentID的数组。 由于它实际上是学生已经签出的书的列表,因此您首先需要在booksListbooksList所有studentID的数组,然后可以在结果数组中使用includes 地图

您可以使用Rocky Sims的解决方案,也可以尝试使用

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

暂无
暂无

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

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