假设我有一个数组:
members = [
{name: 'Anna', class: 'one'},
{name: 'Bob', class: 'two'},
{name: 'Chuck', class: 'two'}];
removed = members.myRemoveByClass('two'); //something like
// removed is {name: 'Bob', class: 'two'}
// members is [{name: 'Anna', class: 'one'}, {name: 'Chuck', class: 'two'}]
我正在为 myRemoveByClass
找东西。 ES2015 没问题或使用 Lodash。该阵列将已经订购。 None的 questions我有 seen相当match我是什么looking为了。
最佳答案
您可以使用 Array.prototype.findIndex() :
The
findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating no element passed the test.
然后 splice()
索引的对象。
var members = [
{name: 'Anna', class: 'one'},
{name: 'Bob', class: 'two'},
{name: 'Chuck', class: 'two'}];
var idx = members.findIndex(p => p.class=="two");
var removed = members.splice(idx,1);
console.log(removed);
console.log(members);
关于javascript - 查找并删除 Javascript 对象数组中的第一个匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53534721/