javascript 用其他数组筛选数组

2izufjch  于 2023-02-15  发布在  Java
关注(0)|答案(1)|浏览(133)

我有两个数组

firstArray = ['10','12'];
secondArray = [{"id":"10", "name":"name 10"}, {"id":"11", "name":"name 11"}, {"id":"12", "name":"name 12"}];

这里我想从第二个数组中删除条目{"id":"11", "name":"name 11"},因为ID 11不在第一个数组中。

secondArray = [{"id":"10", "name":"name 10"}, {"id":"12", "name":"name 12"}];

我该怎么做呢?
我不确定,下面的代码可以给出正确的输出

const firstArray = ['10','12'];
let secondArray = [{"id":"10", "name":"name 10"}, {"id":"11", "name":"name 11"}, {"id":"12", "name":"name 12"}];
secondArray = secondArray.filter((o) => firstArray.findIndex((obj)=> obj.id === o.id)!=-1 );
console.log(secondArray);
jm2pwxwz

jm2pwxwz1#

您可以通过检查数组是否包含所需的id进行过滤。

const
    unwanted = ['10', '12'],
    data = [{ id: "10", name: "name 10" }, { id: "11", name: "name 11" }, { id: "12", name: "name 12" }],
    result = data.filter(({ id }) => unwanted.includes(id));

console.log(result);

相关问题