javascript - 过滤对象数组
问题描述
我试图检查数组中的一个对象是否具有 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');
}
解决方案
然后只需!==
使用===
.
但是你可以使用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 - 应用内浏览器中缺少 Facebook 登录按钮
- php - 每个循环的 Laravel 都会产生额外的列表
- django - 在 django 中查询?
- delphi - FastMM:如何为所有 unicode 或 ansi 字符串注册预期内存泄漏?
- php - PHP CLI 运行外部程序
- ios - 如何为泛型类及其子类提供协议方法的默认实现?
- html - 如何在两个不同的页面之间链接
- ruby-on-rails - Ruby on Rails - 加载活动记录的记录范围与收集方法
- python - 使用 Cloud Composer 和 Celery Executor 在安全网络中的远程工作人员上运行作业
- firebase - Firebase 动态链接社交信息