我一直在尝试几种方法,如何在一个数组中找到一个对象,其中ID = var,如果找到,从数组中删除对象,并返回新的对象数组。

数据:

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

当前回答

ES6原生解决方案:

const pos = data.findIndex(el => el.id === ID_TO_REMOVE);
if (pos >= 0)
    data.splice(pos, 1);

如果你确定元素在数组中:

data.splice(data.findIndex(el => el.id === ID_TO_REMOVE), 1);

原型:

Array.prototype.removeByProp = function(prop,val) {
    const pos = this.findIndex(x => x[prop] === val);
    if (pos >= 0)
        return this.splice(pos, 1);
};

// usage:
ar.removeByProp('id', ID_TO_REMOVE);

http://jsfiddle.net/oriadam/72kgprw5/

注意:这将就地移除项目。如果你需要一个新的数组,使用过滤器在前面的答案中提到的。

其他回答

如果测试严格相等,请确保将对象id强制为整数:

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

Demo

我可以grep数组的id,但我怎么能删除整个对象的id == 88

简单地通过相反的谓词进行过滤:

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

也许你正在寻找$.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
});

您可以简化它,在这里实际上不需要使用jQuery。

var id = 88;

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

只需遍历列表,找到匹配的id,拼接,然后中断以退出循环。

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

这里我们得到了id值为88的对象的索引

const index = data.findIndex(item => item.id === "88");
console.log(index); // 0

我们使用splice函数从数据数组中删除指定的对象

data.splice(index,1);
console.log(data); // [{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}]