Javascript:从对象数组中删除元素 [英] Javascript: Remove an element from an array of objects

查看:137
本文介绍了Javascript:从对象数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组:

var items = [{ id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3"}];

我有以下对象:

var itemToRemove = { id: 2, text: "test2" };

如果 itemToRemove 我想按ID检查存在于项目数组中。

I want to check by id if itemToRemove exists in the items array.

并删除它:

  // pseudo code
  items.remove(itemToRemove);

我经历了javascript数组方法,但没有找到任何可以完成这项工作的方法。谢谢!

I went through javascript array methods but found nothing that will do the job. Thanks!

推荐答案

使用普通循环遍历数组,然后使用 splice()

Traverse the array by using a plain loop and then remove the matching item by using splice():

for( var i=0; i<items.length; i++ ) {
  if( items[i].id == itemToRemove.id ) {
    items.splice( i, 1 );  // remove the item
    break; // finish the loop, as we already found the item
  }
}

这篇关于Javascript:从对象数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆