删除项目对象javascript

时间:2016-09-25 02:17:36

标签: javascript jquery object

我有以下对象:

[{
    "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"
}]

它可以吗?

1 个答案:

答案 0 :(得分: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);
    }
});