【问题标题】:remove item object javascript [duplicate]删除项目对象javascript [重复]
【发布时间】:2016-09-25 02:17:36
【问题描述】:

我有以下对象:

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

可以吗?

【问题讨论】:

  • 转到 MDN 并阅读有关 Array.prototype 的信息。不要跑到 stackoverflow 问这样的基本问题。这也与jquery 无关
  • 你有一个对象数组,而不仅仅是一个对象。您要求删除数组中的一个索引项。见:Array.prototype.splice()
  • Bonsoir Elliot : array.splice(0,1)
  • @mayken 我试试这个功能

标签: javascript jquery object


【解决方案1】:

类似下面的代码?

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);
    }
});

【讨论】:

  • 是的,我理解这个逻辑......但试图找到一些函数来删除该项目,而不是创建一个新项目
  • 感谢您的帮助,我现在很清楚 :)
  • @funktasmas 没问题!很高兴我能帮上忙!如果有帮助,请记住接受答案,这样它也可以帮助其他人。很高兴我能帮上忙。
猜你喜欢
  • 2015-09-10
  • 1970-01-01
  • 2016-07-02
  • 2020-10-25
  • 2015-03-16
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多