javascript - 查找并删除 Javascript 对象数组中的第一个匹配元素

标签 javascript arrays

假设我有一个数组:

    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。该阵列将已经订购。 Nonequestions我有 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/

相关文章:

javascript - 导航子菜单在页面加载时未最小化

javascript - Backbone.js 空数组属性

c# - Array.sort 函数影响数组,我认为它不应该影响

javascript - 如何在数量框中添加增加和减少按钮

javascript - 在 Chrome 中获取 getSVGDocument 的未定义结果,在 Firefox 中工作正常

javascript - 更新到 jest 24 后 transformIgnorePatterns 不工作

php - 在数组中搜索两个值

javascript - fs.createReadStream 之后代码块未执行

javascript - json如何将行转换为列

Java:希望忽略某些超出范围的行