gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:24:59 26 4
gpt4 key购买 nike

假设我有一个数组:

    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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com