首页 > 解决方案 > 过滤对象数组

问题描述

我试图检查数组中的一个对象是否具有 2 的 id,如果是,请删除该对象。list.filter(e => e.id === 2)返回[ { name: 'bread', id: 2 } ]这是我要删除的部分,但是如果我通过执行if(list.indexOf(list.filter(e => e.id === 2)) != -1)它来检查它是否在数组中,则返回 -1 表示它不在列表中。任何帮助将不胜感激!

var list = new Array();
list.push({name: 'apple', id: 1})
list.push({name: 'bread', id: 2})
console.log(list.filter(e => e.id === 2));
console.log(list);
if(list.indexOf(list.filter(e => e.id === 2)) != -1) {
    list.splice(list.indexOf(list.filter(e => e.name === 2)));
    console.log(list);
} else {
    console.log('The id of 2 has not been found');
}

标签: javascriptnode.js

解决方案


然后只需!==使用===.

但是你可以使用find方法。

var elem = list.find(e => e.id === 2);
if(elem)
   list = list.filter(e => e.id !== 2);
else
   console.log('The id of 2 has not been found');

推荐阅读