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

当前回答

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,拼接,然后中断以退出循环。

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

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

var data = $.grep(data, function(e){ 
     return e.id != 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!"}]

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/

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

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兼容。