2016-09-25 41 views
-3

我有以下對象:刪除項目對象的JavaScript

[{ 
    "id": 2, 
    "price": 2000, 
    "name": "Mr Robot T1", 
    "image": "http://placehold.it/270x335" 
}, { 
    "id": 1, 
    "price": 1000, 
    "name": "Mr Robot T2", 
    "image": "http://placehold.it/270x335" 
}] 

和我要的是刪除第一個項目(ID = 1),結果是:

[{ 
    "id": 2, 
    "price": 2000, 
    "name": "Mr Robot T1", 
    "image": "http://placehold.it/270x335" 
}] 

,因爲它可以做?

+2

轉到MDN並閱讀有關Array.prototype。不要跑到stackoverflow問這樣的基本問題。此外,這與jQuery沒有任何關係。 – Azamantes

+0

你有一個對象數組,而不僅僅是一個對象。您要求刪除數組中的一個索引項目。參見:['Array.prototype.splice()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) – Makyen

+0

Bonsoir Elliot:'array.splice (0,1)' – jrbedard

回答

0

像下面的代碼?

var array = [{ 
    "id": 2, 
    "price": 2000, 
    "name": "Mr Robot T1", 
    "image": "http://placehold.it/270x335" 
}, { 
    "id": 1, 
    "price": 1000, 
    "name": "Mr Robot T2", 
    "image": "http://placehold.it/270x335" 
}]; 

var newArray = []; 

array.forEach(function(item){ 
    if (item.id != 1) { 
     newArray.push(item); 
    } 
}); 

基本上通過你的陣列將循環,並沒有一個id = 1所有元素都會被推到變量newArray

編輯

爲了刪除的項目,你可以隨時splice它。像下面這樣。

var array = [{ 
    "id": 2, 
    "price": 2000, 
    "name": "Mr Robot T1", 
    "image": "http://placehold.it/270x335" 
}, { 
    "id": 1, 
    "price": 1000, 
    "name": "Mr Robot T2", 
    "image": "http://placehold.it/270x335" 
}]; 

array.forEach(function(item, index){ 
    if (item.id == 1) { 
     array.splice(index, 1); 
    } 
}); 
+0

是的,我理解這個邏輯......但是試圖找到一些函數來刪除這個項目,而不是創建一個新的 – funktasmas

+0

感謝您的幫助,它是現在明白:) :) – funktasmas

+0

@funktasmas沒問題!很高興我能幫上忙!請記住接受答案,如果有幫助,也可以幫助其他人。很高興我能幫助你。 –