Rav*_*i K 1 javascript arrays loops object reactjs
我有以下来自后端的数据。
priorities: [ 'get license', 'enroll college' ];
Run Code Online (Sandbox Code Playgroud)
现在,我在前端有一个硬编码的对象列表。
studentPriorities = [
{
prioritiesTitle: "get license",
prioritiesDescription: "go to DMV and get your license"
},
{
prioritiesTitle: "enroll college",
prioritiesDescription: "gather fees and enroll for college"
},
{
prioritiesTitle: "give exams",
prioritiesDescription: "study hard for the exams"
}
]
Run Code Online (Sandbox Code Playgroud)
在任何时候,我都会得到 2 个优先级作为后端响应。我需要搜索我的硬编码对象数组并获取最终数据,如下所示。
mappedStudentPriorities = [
{
prioritiesTitle: "get license",
prioritiesDescription: "go to DMV and get your license"
},
{
prioritiesTitle: "enroll college",
prioritiesDescription: "gather fees and enroll for college"
}
]
Run Code Online (Sandbox Code Playgroud)
有人可以建议我如何实现这一目标吗?
这可以简单地使用Array.filter&完成Array.includes。
使用Array.includes可以检查元素是否包含在数组中,使用Array.filter可以得到满足条件的过滤结果。
const priorities = [ 'get license', 'enroll college' ];
const studentPriorities = [
{
prioritiesTitle: "get license",
prioritiesDescription: "go to DMV and get your license"
},
{
prioritiesTitle: "enroll college",
prioritiesDescription: "gather fees and enroll for college"
},
{
prioritiesTitle: "give exams",
prioritiesDescription: "study hard for the exams"
}
];
const result = studentPriorities.filter(({ prioritiesTitle }) => priorities.includes(prioritiesTitle));
console.log(result);Run Code Online (Sandbox Code Playgroud)