如何从一个数组中删除与另一个ID数组匹配的对象

3

我有一个ID数组,还有另一个对象数组。我想删除那些与ID数组匹配的对象。以下是相应的伪代码。可以有人帮我找到最好的方法吗?

const ids = ['1', '2'];

const objs = [
  {
  id: "1", 
  name : "one",
 },
 {
  id: "1", 
  name : "two"
},
{
  id: "3", 
  name : "three",
},
{
  id: "4", 
  name : "four"
},
];

ids.forEach(id => {
  const x =   objs.filter(obj =>  obj.id !== id )
  console.log('x ==', x);
});

4个回答

4

使用 filterincludes 方法。

const ids = ["1", "2"];

const objs = [
  {
    id: "1",
    name: "one",
  },
  {
    id: "1",
    name: "two",
  },
  {
    id: "3",
    name: "three",
  },
  {
    id: "4",
    name: "four",
  },
];

const res = objs.filter(({ id }) => !ids.includes(id));

console.log(res);


4
你可以将 ids 放入一个 Set 中,然后使用 .filter 迭代对象数组并使用 .has 检查是否存在于此 set 中的 id

const ids = ['1', '2'];
const objs = [
  { id: "1", name : "one" },
  { id: "1", name : "two" },
  { id: "3", name : "three" },
  { id: "4", name : "four" },
];

const set = new Set(ids);
const arr = objs.filter(obj => !set.has(obj.id));

console.log(arr);


2

第一个要求 -> 您必须检查id数组中的所有元素,使用数组的内置方法array.includes()或indexof方法进行操作。

第二个要求 -> 挑选出与您的第一个要求不匹配的元素,也就是筛选数组。

合并两个要求。

arr = arr.filter(x => !ids.includes(x.id))

酷炫的es6解构语法
arr = arr.filter(({id}) => !ids.includes(id))

0
const ids = ['1', '2'];
const objs = [
  {
  id: "1", 
  name : "one",
 },
 {
  id: "1", 
  name : "two"
},
{
  id: "3", 
  name : "three",
},
{
  id: "4", 
  name : "four"
},
];
let  arr = objs.filter(function(i){
      return ids.indexOf(i.id) === -1;
    });
console.log(arr)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接