繁体   English   中英

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

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

我得到了一个 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); });

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

您可以将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);

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

第二个要求 -> 挑选出与您的第一个要求不匹配的元素,这意味着过滤数组。

合二为一

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

很酷的 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