【问题标题】:Javascript: Remove an element from an array of objectsJavascript:从对象数组中删除一个元素
【发布时间】:2016-05-12 19:25:23
【问题描述】:

我有一个对象数组:

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

我有以下对象:

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

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

并删除它:

  // pseudo code
  items.remove(itemToRemove);

我浏览了 javascript 数组方法,但没有发现任何可以完成这项工作的方法。谢谢!

【问题讨论】:

标签: javascript


【解决方案1】:

使用filter:

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

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

【讨论】:

  • +1,但这不适用于糟糕的(即 IE add the filter method 到 Array 对象。
  • @Robusto if (![].filter) Array.prototype.filter = function (callback, that) { var index = 0, length = this.length, list = []; while (index < length) { var item = this[index]; if (callback.call(that, item, index++, this)) list.push(item); } return list; };
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-03-21
    • 2020-01-31
    • 2021-08-18
    • 2011-03-14
    • 2016-11-08
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多