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

时间:2018-11-29 08:31:13

标签: 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。该阵列将已经订购。 None中的questionsseen match的用途looking

8 个答案:

答案 0 :(得分:6)

您可以创建自己的Array类:

 class Members extends Array {
   removeByClass(className) {
     for(const [index, member] of this.entries())
        if(member.class === className) 
           return this.splice(index, 1)[0];
   }
}

用作

 const members = new Members([ {/*...*/}, {/*...*/} ]);
 members.removeByClass("...");

PS:“类”是一个非常糟糕的名称,因为它是保留关键字

答案 1 :(得分:2)

这也可以

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Laravel</title>
    </head>
    <body>
        <div class="content" id="app">
            <div class="title m-b-md">
                <hello-world-component></hello-world-component>
            </div>
        </div>
    </body>
<script src="{{ asset('js/app.js') }}"></script>
</html>

答案 2 :(得分:2)

您可以找到第一次出现的索引,并检查该索引并从数组中拼接对象。

var members = [{ name: 'Anna', class: 'one' }, { name: 'Bob', class: 'two' }, { name: 'Chuck', class: 'two' }],
    index = members.findIndex(o => o.class === 'two'),
    removed = index !== -1 && members.splice(index, 1);

console.log(removed);
console.log(members);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:2)

您可以使用Array.prototype.findIndex()

  

findIndex()方法返回数组满足提供的测试功能的第一个元素的 index 。否则,它返回-1,表示没有元素通过测试。

然后通过该 index 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);

答案 4 :(得分:2)

您可以使用withoutfindWhere

var arr = _.without(members , _.findWhere(members , {
 class: "two"
}));

答案 5 :(得分:1)

简单地:

function removeByClass(obj, prop) {
    for (let i = 0; i < obj.length; i++) {
        if (obj[i].class == prop) obj.splice(i, 1);
    }   
}

答案 6 :(得分:1)

您可以使用some方法找到需要删除的member,然后返回true停止循环。

let members = [
  {name: 'Anna', class: 'one'}, 
  {name: 'Bob', class: 'two'},  
  {name: 'Chuck', class: 'two'}
];

function myRemoveByClass(members, className) {
  let foundMember = null;
  members.some((member, index) => {
    if (member.class == className) {
      members.splice(index, 1);
      foundMember = member;
      return true;
    }
  });
  
  return foundMember;
}

let removed = myRemoveByClass(members, 'two');
console.log(removed);
console.log(members);

如乔纳斯(Jonas)指出的here,您应该避免使用class,因为它是保留字。

答案 7 :(得分:1)

您可以将Array.prototype.find()Array.prototype.splice()组合使用

代码示例:

const members = [{ name: 'Anna', class: 'one' }, { name: 'Bob', class: 'two' }, { name: 'Chuck', class: 'two' }];

members.find((o, i) => {
  if (o.class === 'two') {
    members.splice(i, 1); // Find and remove first matching element
    return true;
  }
  return false;
});

console.log(members);