我一直在尝试几种方法,如何在一个数组中找到一个对象,其中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!"}
]

当前回答

假设id是唯一的,你只需要删除一个元素拼接就可以了:

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

console.table(data);

$.each(data, function(i, el){
  if (this.id == id){
    data.splice(i, 1);
  }
});

console.table(data);

其他回答

在ES6/2015中有一个新方法,使用findIndex和数组展开操作符来做到这一点:

const index = data.findIndex(obj => obj.id === id);
const newData = [
    ...data.slice(0, index),
    ...data.slice(index + 1)
]

你可以像这样把它转换成一个函数供以后重用:

function remove(array, key, value) {
    const index = array.findIndex(obj => obj[key] === value);
    return index >= 0 ? [
        ...array.slice(0, index),
        ...array.slice(index + 1)
    ] : array;
}

这样,你可以使用一个方法删除不同键的项(如果没有符合条件的对象,你会返回原始数组):

const newData = remove(data, "id", "88");
const newData2 = remove(data, "name", "You are awesome!");

或者你可以把它放在你的Array.prototype上:

Array.prototype.remove = function (key, value) {
    const index = this.findIndex(obj => obj[key] === value);
    return index >= 0 ? [
        ...this.slice(0, index),
        ...this.slice(index + 1)
    ] : this;
};

然后这样用:

const newData = data.remove("id", "88");
const newData2 = data.remove("name", "You are awesome!");

Sift是一个功能强大的集合过滤器,可以用于这样的操作和更高级的操作。它在浏览器的客户端或Node.js的服务器端工作。

var collection = [
    {"id":"88",  "name":"Lets go testing"},
    {"id":"99",  "name":"Have fun boys and girls"},
    {"id":"108", "name":"You are awesome!"}
];
var sifted = sift({id: {$not: 88}}, collection);

它支持像$in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type和$regex这样的过滤器,并努力与MongoDB集合过滤api兼容。

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

如果你用的是jQuery,那就用jQuery吧。Grep是这样的:

items = $.grep(items, function(item) { 
  return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]

使用ES5 Array.prototype.filter:

items = items.filter(function(item) { 
  return item.id !== '88'; 
});
// items => [{ id: "99" }, { id: "108" }]

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

var id = 88;

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

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

我同意前面的答案。如果你想通过id找到一个对象并删除它,一个简单的方法就像下面的代码:

var obj = JSON.parse(data);
var newObj = obj.filter(item => item.Id != 88);