我正在尝试检查数组中的某个对象的 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/