2016-09-25 39 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没问题!很高兴我能帮上忙!请记住接受答案,如果有帮助,也可以帮助其他人。很高兴我能帮助你。 –