2013-09-23 60 views
1

我有对象的数组:使用Javascript:从对象的数组中删除的元素

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

我有以下目的:

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

我想通过ID来检查是否存在于itemToRemoveitems阵列。

,并删除它:

// pseudo code 
    items.remove(itemToRemove); 

我通过JavaScript阵列的方法去,但没有发现任何将做的工作。谢谢!

+0

可能的重复[如何从数组中删除项目?](https://stackoverflow.com/questions/3954438/how-to-remove-item-from-array-by-value) – pscl

回答

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 
    } 
} 
2

使用filter

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

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

+0

+1,但这在蹩脚的(即IE <9)浏览器中不起作用。你必须使用某种形式的[添加过滤器方法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)到Array目的。 – Robusto

+0

@Robusto'if(![] .filter)Array.prototype.filter = function(callback,that){var index = 0,length = this.length,list = []; while(index