根据内部数组的值过滤对象数组

时间:2020-09-10 13:48:00

标签: typescript

我想从数组courses中仅选择在fieldIds数组中具有至少一个ID为ID的字段的课程。下面是thw数组的格式:

courses = [
    {id: 5, name:"some name1", fields:[{id: 28, name:"field name"}, {id: 29, name:"field name2"}]},
    {id: 18, name:"some name2", fields:[{id: 11, name:"field name"}, {id: 28, name:"field name2"}]},
    {id: 7, name:"some name3", fields:[{id: 29, name:"field name"}, {id: 9, name:"field name2"}]}
]

fieldIds = [29, 9]

所以结果应该是:

courses = [
    {id: 5, name:"some name1", fields:[{id: 28, name:"field name"}, {id: 29, name:"field name2"}]},
    {id: 7, name:"some name3", fields:[{id: 29, name:"field name"}, {id: 9, name:"field name2"}]}
]

这是我尝试过的,我总是得到相同的数组,它什么也不会改变

fieldIds.map(fieldId => {
    courses = courses.filter(course => course.fields.map(f => f.id == fieldId);
});
尝试按以下方式尝试this question的响应后,

编辑

fieldIds.map(fieldId => {
    courses = courses.filter(course => course.fields.some(f => f.id == fielded))
}

例如,如果fieldIds包含几个ID,则该函数返回属于所有字段的课程。 (并且我要提取至少具有所选字段之一的课程)

1 个答案:

答案 0 :(得分:2)

这是可行的解决方案:

const courses = [
    {id: 5, name:"some name1", fields:[{id: 28, name:"field name"}, {id: 29, name:"field name2"}]},
    {id: 18, name:"some name2", fields:[{id: 11, name:"field name"}, {id: 28, name:"field name2"}]},
    {id: 7, name:"some name3", fields:[{id: 29, name:"field name"}, {id: 9, name:"field name2"}]}
];

const fieldIds = [29, 9];

const filtered_courses = courses.filter(course => course.fields.some(field => fieldIds.includes(field.id)));

console.log(filtered_courses);

Filter具有条件( some )的 courses 数组,该数组用于验证以下内容中的至少一个元素: fields 数组与 fieldIds 数组具有相等的值。

PS:如果 fields 数组和 fieldIds 数组以ASC或DESC顺序排序,则“算法”要快得多,因为 some 方法更早返回。