简体   繁体   English

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

[英]How to remove objects from an array which match another array of ids

I got an array of id's.我得到了一个 id 数组。 I also have another array of objects.我还有另一个对象数组。 I would like to remove those objects which match with the array of id's.我想删除那些与 id 数组匹配的对象。 Below is the pseudo code for the same.下面是相同的伪代码。 Can someone help me with the best approch?有人可以用最好的方法帮助我吗?

 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); });

Use filter and includes method使用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);

You can put the ids in a Set and use .filter to iterate over the array of objects and .has to check if the id is in this set :您可以将ids放入Set并使用.filter遍历对象数组,并.has检查id是否在此set中:

 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);

1st requirement -> you have to check for all elements in id array way to do that using array's built in method is array.includes() or indexof methods第一个要求->您必须检查 id 数组中的所有元素,才能使用数组的内置方法是 array.includes() 或 indexof 方法

2nd Requirement -> pick out elements not matching with ur 1st requirement which means filter the array.第二个要求 -> 挑选出与您的第一个要求不匹配的元素,这意味着过滤数组。

Combile two合二为一

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

Cool es6 destructung syntax很酷的 es6 解构语法

arr = arr.filter(({id}) => !ids.includes(id))
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM