繁体   English   中英

Javascript:从对象数组中删除元素

[英]Javascript: Remove an element from an array of objects

我有一个对象数组:

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

我有以下对象:

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

我想通过id检查items数组中是否存在itemToRemove

并将其删除:

  // pseudo code
  items.remove(itemToRemove);

我经历了javascript数组方法,但没有发现任何可以做的工作。 谢谢!

使用filter

items.filter(function (item) {
    return item.id !== 2 || item.text !== "text2";
});

改变原始数组通常不是一个好主意,否则我会推荐Sirko的答案。 filter方法会产生一个全新的数组。 它不会改变原始数组。

使用普通循环遍历数组,然后使用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
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM