2013-04-22 43 views
1

我怎樣才能把一個數組的對象通過ID例如:使用javascript從數組中刪除對象?

users = [{id: "10051", name: "Mike Coder"},{id: "4567", name: "Jhon Second"}] 

說我想用javascript刪除ID爲「10051」的用戶,我試圖通過互聯網搜索,但沒有找到任何東西?

加我不想使用下劃線!

+1

你得到答案瞭如何構建一個新的,過濾陣列,但你的問題似乎問如何從目前的陣列中刪除。你需要哪一個? – Pokey 2013-04-22 00:42:08

回答

4

加我不想使用下劃線!

這種本地方法是.filter()

var removeId = "4567"; 
users = users.filter(function (user) { return user.id !== removeId; }); 

注意,它需要發動機是ES5-compatible(或polyfill)。

2
for (var i = 0; i < users.length; ++i) 
{ 
    if (users[i].id == "10051") 
    { 
     users[i].splice(i--, 1); 
    } 
} 
2

您可以使用.filter數組的方法。

users = users.filter(function(el) {return el.id !== '10051'}); 
1
var users= [{id:"10051", name:"Mike Coder"},{id:"4567", name:"Jhon Second"}]; 

/* users.length= 2 */ 

function removebyProperty(prop, val, multiple){ 
    for(var i= 0, L= this.length;i<L;i++){ 
     if(i in this && this[i][prop]=== val){ 
      this.splice(i, 1); 
      if(!multiple) i= L; 
     } 
    } 
    return this.length; 
} 

removebyProperty.call(用戶, 'ID', 「10051」);

返回值:(數字)1

+0

我很想知道爲什麼在函數中使用'this'和'.call()',而不是僅僅接收數組作爲參數,因此不需要'.call()'。 – Pokey 2013-04-22 00:51:57

+0

@Pokey-好吧,它是一個狹隘的聚焦函數,它在一個特定類型的對象上完成一件事。我很喜歡用它作爲對象的一種方法,所以我把它稱爲一個。 – kennebec 2013-04-22 05:04:56