gpt4 book ai didi

javascript - 将一个对象数组中的属性值映射到另一个对象数组 Javascript 中的属性

转载 作者:行者123 更新时间:2023-11-30 11:25:57 25 4
gpt4 key购买 nike

我有两个对象数组:

courses = [ { _id: 999, courseCode: "Eng1" },
{ _id: 777, courseCode: "Sci1" },
{ _id: 666, courseCode: "Eng2" },
{ _id: 888, courseCode: "Sci2" } ]

sectionCourses = [ { sectionCode: "1A", courseId: "999" },
{ sectionCode: "1A", courseId: "777" },
{ sectionCode: "2A", courseId: "666" },
{ sectionCode: "2A", courseId: "888" } ]

我想过滤 courses 数组,使其只包含不在某个部分的类(class)。例如,如果我选择带有 sectionCode: "2A" 的部分,则 courses 数组应该只包含

courses = [ { _id: 999, courseCode: "Eng1" },
{ _id: 777, courseCode: "Sci1" },
{ _id: 888, courseCode: "Sci2" } ]

我试过这样做:

 courses = courses.filter(c => !(sectionCourses.includes(c._id)))

但我知道这是不完整的,因为我不知道如何访问 sectionCourses 中的 courseId

请帮忙。

最佳答案

您不能使用 .includes() 方法通过其 _id 查找整个对象,includes 比较整个对象而不搜索特定属性.

这里你可以做的是根据你提供的sectionCode得到一个courseIds数组,然后过滤掉他们的_id的类(class) 不存在于此 ids 数组中:

function getCourses(catCode) {

var coursesIdstoIgnore = sectionCourses.filter(s => s.sectionCode === catCode).map(s => s.courseId);
return courses.filter(c => coursesIdstoIgnore.indexOf(c["_id"].toString()) == -1);
}

演示:

var courses = [{
_id: 999,
courseCode: "Eng1"
},
{
_id: 777,
courseCode: "Sci1"
},
{
_id: 666,
courseCode: "Eng2"
},
{
_id: 888,
courseCode: "Sci2"
}
];

var sectionCourses = [{
sectionCode: "1A",
courseId: "999"
},
{
sectionCode: "1A",
courseId: "777"
},
{
sectionCode: "2A",
courseId: "666"
},
{
sectionCode: "2A",
courseId: "888"
}
];

function getCourses(catCode) {
var cousesIdstoIgnore = sectionCourses.filter(s => s.sectionCode === catCode).map(s => s.courseId);
console.log(cousesIdstoIgnore);

return courses.filter(c => cousesIdstoIgnore.indexOf(c["_id"].toString()) == -1);

}

var results = getCourses("2A");


console.log(results);

关于javascript - 将一个对象数组中的属性值映射到另一个对象数组 Javascript 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com