2014-02-09 38 views
75

我一直在嘗試幾種方法如何找到一個數組中的對象,其中ID = var,如果找到,從數組中刪除對象並返回新數組的物體。JavaScript找到並刪除基於鍵值的數組中的對象

數據:

[ 
    {"id":"88","name":"Lets go testing"}, 
    {"id":"99","name":"Have fun boys and girls"}, 
    {"id":"108","name":"You are awesome!"} 
] 

我能夠搜索到使用jQuery的grep $數組;

var id = 88; 

var result = $.grep(data, function(e){ 
    return e.id == id; 
}); 

但我怎麼能刪除整個對象時,ID = = 88,並返回這樣的數據:

數據:

[ 
    {"id":"99","name":"Have fun boys and girls"}, 
    {"id":"108","name":"You are awesome!"} 
] 
+0

如何使用'切片'功能和一點'for'循環? –

+0

當然,但是,我寫這個問題的原因,是因爲我卡住了;)任何片段? – Tom

+0

檢查這個帖子http://stackoverflow.com/questions/10827894/how-do-i-slice-an-array-from-an-array-of-object-literals –

回答

99

我可以grep此ID的數組,但我怎麼能刪除整個對象其中id == 88

由相對謂詞只需進行過濾:

var data = $.grep(data, function(e){ 
    return e.id != id; 
}); 
+9

這個答案爲jQuery提供了最簡潔和慣用的解決方案 – Bryan

+1

在你想要刪除id = something的所有項目的情況下很好......但是在使用$ .grep時要小心,因爲它會搜索整個數組對於長陣列來說效率不高。有時你只需要檢查一個給定的ID是否存在於數組中,那麼最好使用另一種迭代方法;) – julianox

+0

這不會從列表中刪除該對象 –

60

您可以簡化這一點,沒什麼這裏不需要使用jquery。

var id = 88; 

for(var i = 0; i < data.length; i++) { 
    if(data[i].id == id) { 
     data.splice(i, 1); 
     break; 
    } 
} 

通過名單只是想迭代,找到匹配的ID,拼接,再突破,退出你的循環

+15

+1,但您應該提及,這隻會刪除與之匹配的第一個項目。 – Bergi

+4

...如果你需要刪除每個匹配的項目,按照相反的順序循環'i = data.length; i> 0;我 - '並且不要使用'break'。 –

+1

'i = data.length'會破壞任何'data [i]',它應該像'i = data.length -1; i> -1;我 - ' – distante

0

確保你要挾的對象ID爲整數,如果你測試全等:

var result = $.grep(data, function(e, i) { 
    return +e.id !== id; 
}); 

Demo

1
var items = [ 
    {"id":"88","name":"Lets go testing"}, 
    {"id":"99","name":"Have fun boys and girls"}, 
    {"id":"108","name":"You are awesome!"} 
]; 

如果您正在使用jQuery,使用jQuery.grep這樣的:

items = $.grep(items, function(item) { 
    return item.id !== '88'; 
}); 
// items => [{ id: "99" }, { id: "108" }] 

使用ES5 Array.prototype.filter

items = items.filter(function(item) { 
    return item.id !== '88'; 
}); 
// items => [{ id: "99" }, { id: "108" }] 
+1

Noooooo!不要使用'jQuery'作爲過濾器。 – Bergi

+1

同意!使用grep解決方案是使用jQuery的正確解決方案。 – nekman

1
Array.prototype.removeAt = function(id) { 
    for (var item in this) { 
     if (this[item].id == id) { 
      this.splice(item, 1); 
      return true; 
     } 
    } 
    return false; 
} 

這應該做的伎倆,jsfiddle

4

也許你正在尋找$.grep()功能:

arr = [ 
    {"id":"88","name":"Lets go testing"}, 
    {"id":"99","name":"Have fun boys and girls"}, 
    {"id":"108","name":"You are awesome!"} 
]; 

id = 88; 
arr = $.grep(arr, function(data, index) { 
    return data.id != id 
}); 
6

假設ID是唯一的,您只需要刪除一個元素splice應訣竅:

var data = [ 
{"id":"88","name":"Lets go testing"}, 
{"id":"99","name":"Have fun boys and girls"}, 
{"id":"108","name":"You are awesome!"} 
], 
id = 88; 

console.table(data); 

$.each(data, function(i, el){ 
    if (this.id == id){ 
     data.splice(i, 1); 
    } 
}); 

console.table(data); 
+0

您的回調函數中的元素向後。它應該是'每個(數據,功能(idx,ele)',我會在30分鐘後通知你我浪費了計算出來:) – CSharper

+0

哎呀。在這種情況下我能做的至少是更新我的答案。我對你浪費了30分鐘的生命感到非常失望。 –

0

如果您使用下劃線js,很容易r根據鍵移除對象。 http://underscorejs.org。 例子:

var temp1=[{id:1,name:"safeer"}, //temp array 
      {id:2,name:"jon"}, 
      {id:3,name:"James"}, 
      {id:4,name:"deepak"}, 
      {id:5,name:"ajmal"}]; 

    var id = _.pluck(temp1,'id'); //get id array from temp1 
    var ids=[2,5,10];    //ids to be removed 
    var bool_ids=[]; 
    _.each(ids,function(val){ 
    bool_ids[val]=true; 
    }); 
    _.filter(temp1,function(val){ 
    return !bool_ids[val.id]; 
    }); 
2

sift是這樣的操作和更先進的人一個強大的集過濾器。它在node.js的瀏覽器或服務器端運行客戶端。

var collection = [ 
    {"id":"88","name":"Lets go testing"}, 
    {"id":"99","name":"Have fun boys and girls"}, 
    {"id":"108","name":"You are awesome!"} 
]; 
var sifted = sift({id: {$not: 88}}, collection); 

它支持像$in$nin$exists$gte$gt$lte$lt$eq$ne$mod$all$and$or$nor$not$size$type$regex,努力過濾器與MongoDB收集過濾API兼容。

+0

爲什麼沒有upwotes?如果這個東西寫得很好,沒有可怕的錯誤,它應該是非常有用的。 –

41

這裏是一個解決方案,如果你不使用jQuery:

myArray = myArray.filter(function(obj) { 
    return obj.id !== id; 
}); 
+1

這比在子數組上執行'findIndex()'然後'拼接(索引,1)'更好嗎? – Alex

+0

splice會改變原始數組。有了過濾器,你可以選擇。 – velop

5

有使用findIndex和陣列蔓延運營商爲此在ES6/2015年的新方法:

const index = data.findIndex(obj => obj.id === id); 
const newData = [ 
    ...data.slice(0, index), 
    ...data.slice(index + 1) 
] 

可以打開它變成一個功能,以供以後重用,如下所示:

function remove(array, key, value) { 
    const index = array.findIndex(obj => obj[key] === value); 
    return index >= 0 ? [ 
     ...this.slice(0, index), 
     ...this.slice(index + 1) 
    ] : this; 
} 

這樣你就可以通過不同的方式刪除項目使用一種方法鍵(如果沒有對象符合標準,你會得到原始數組返回):

const newData = remove(data, "id", "88"); 
const newData2 = remove(data, "name", "You are awesome!"); 

或者你可以把它放在你Array.prototype:

Array.prototype.remove = function (key, value) { 
    const index = this.findIndex(obj => obj[key] === value); 
    return index >= 0 ? [ 
     ...this.slice(0, index), 
     ...this.slice(index + 1) 
    ] : this; 
}; 

並使用它這樣:

const newData = data.remove("id", "88"); 
const newData2 = data.remove("name", "You are awesome!"); 
相關問題