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

当前回答

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

其他回答

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

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

Demo

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" }]
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/

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

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