javascript - 过滤对象数组

标签 javascript node.js

我正在尝试检查数组中的某个对象的 ID 是否为 2,如果是,则删除该对象。 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');
}

最佳答案

然后只需使用 !== 代替 ===

但是你可以使用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');

关于javascript - 过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51768413/

相关文章:

javascript - jQuery 图像交换 - chrome 中的奇怪行为

javascript - switch case 在 JS 中是如何工作的? switch(true) 是什么意思?

javascript - 了解 JSX 中的条件语句

javascript - Electron 托盘应用程序 - 任务栏弹出菜单覆盖的 ui 窗口

javascript - 重定向到 Node JS 路由中的另一个源路径(跨域)

node.js - 如何在 npm install : (npm ERR! install 无法读取依赖项上修复此问题)?

node.js - 如何从Azure Function以二进制数据形式返回base64图像

javascript - 如何修复 Foundation 4 顶部栏中太长的 css 下拉列表?

mysql - ER_CON_COUNT_ERROR : Too many connections knex and bookshelf

Node.js - 使用查询字符串以 GET/POST 形式发送和接收数组