javascript根据键值查找并删除数组中的对象

时间:2022-09-25 07:53:36

I have been trying several approaches on how to find an object in an array, where ID = var, and if found, remove the object from the array and return the new array of objects.

我已经尝试了几种方法来寻找数组中的对象,其中ID = var,如果找到,则从数组中删除对象并返回新的对象数组。

Data:

数据:

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

I'm able to search the array using jQuery $grep;

我可以使用jQuery $grep搜索数组;

var id = 88;

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

But how can I delete the entire object when id == 88, and return data like this:

但是,当id = 88时,如何删除整个对象,并返回如下数据:

Data:

数据:

[
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
]

11 个解决方案

#1


109  

I can grep the array for the id, but how can I delete the entire object where id == 88

我可以提取id的数组,但是如何删除id = 88处的整个对象

Simply filter by the opposite predicate:

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

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

#2


66  

You can simplify this, and there's really no need for using jquery here.

您可以简化它,这里不需要使用jquery。

var id = 88;

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

Just iterate through the list, find the matching id, splice, and then break to exit your loop

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

#3


52  

here is a solution if you are not using jquery:

如果您没有使用jquery,那么这里有一个解决方案:

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});

#4


7  

There's a new method to do this in ES6/2015 using findIndex and array spread operator:

使用findIndex和数组扩展运算符在ES6/2015中有一种新方法:

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

You can turn it into a function for later reuse like this:

您可以将其转换为一个函数,以便以后重用:

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

This way you can to remove items by different keys using one method (and if there's no object that meets the criteria, you get original array returned):

通过这种方式,您可以使用一种方法通过不同的键删除项(如果没有符合条件的对象,则返回原始数组):

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

Or you can put it on your Array.prototype:

或者你可以把它放在你的array.com上。

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

And use it this way:

用这种方式:

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

#5


6  

Assuming that ids are unique and you'll only have to remove the one element splice should do the trick:

假设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);

#6


4  

Maybe you are looking for $.grep() function:

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

#7


2  

sift is a powerful collection filter for operations like this and much more advanced ones. It works client side in the browser or server side in node.js.

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

It supports filters like $in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type, and $regex, and strives to be API-compatible with MongoDB collection filtering.

它支持诸如$in、$nin、$ $、$ $、$gt、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $

#8


1  

Array.prototype.removeAt = function(id) {
    for (var item in this) {
        if (this[item].id == id) {
            this.splice(item, 1);
            return true;
        }
    }
    return false;
}

This should do the trick, jsfiddle

这应该很管用,jsfiddle

#9


1  

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

If you are using jQuery, use jQuery.grep like this:

如果您正在使用jQuery,请使用jQuery。grep这样的:

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

Using ES5 Array.prototype.filter:

使用ES5 Array.prototype.filter:

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

#10


0  

Make sure you coerce the object id to an integer if you test for strict equality:

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

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

Demo

演示

#11


0  

If you are using underscore js, it is easy to remove object based on key. http://underscorejs.org. Example:

如果您正在使用下划线js,那么很容易基于key删除对象。http://underscorejs.org。例子:

  var temp1=[{id:1,name:"safeer"},  //temp array
             {id:2,name:"jon"},
             {id:3,name:"James"},
             {id:4,name:"deepak"},
             {id:5,name:"ajmal"}];

  var id = _.pluck(temp1,'id'); //get id array from temp1
  var ids=[2,5,10];             //ids to be removed
  var bool_ids=[];
  _.each(ids,function(val){
     bool_ids[val]=true;
  });
  _.filter(temp1,function(val){
     return !bool_ids[val.id];
  });

#1


109  

I can grep the array for the id, but how can I delete the entire object where id == 88

我可以提取id的数组,但是如何删除id = 88处的整个对象

Simply filter by the opposite predicate:

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

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

#2


66  

You can simplify this, and there's really no need for using jquery here.

您可以简化它,这里不需要使用jquery。

var id = 88;

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

Just iterate through the list, find the matching id, splice, and then break to exit your loop

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

#3


52  

here is a solution if you are not using jquery:

如果您没有使用jquery,那么这里有一个解决方案:

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});

#4


7  

There's a new method to do this in ES6/2015 using findIndex and array spread operator:

使用findIndex和数组扩展运算符在ES6/2015中有一种新方法:

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

You can turn it into a function for later reuse like this:

您可以将其转换为一个函数,以便以后重用:

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

This way you can to remove items by different keys using one method (and if there's no object that meets the criteria, you get original array returned):

通过这种方式,您可以使用一种方法通过不同的键删除项(如果没有符合条件的对象,则返回原始数组):

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

Or you can put it on your Array.prototype:

或者你可以把它放在你的array.com上。

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

And use it this way:

用这种方式:

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

#5


6  

Assuming that ids are unique and you'll only have to remove the one element splice should do the trick:

假设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);

#6


4  

Maybe you are looking for $.grep() function:

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

#7


2  

sift is a powerful collection filter for operations like this and much more advanced ones. It works client side in the browser or server side in node.js.

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

It supports filters like $in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type, and $regex, and strives to be API-compatible with MongoDB collection filtering.

它支持诸如$in、$nin、$ $、$ $、$gt、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $、$ $

#8


1  

Array.prototype.removeAt = function(id) {
    for (var item in this) {
        if (this[item].id == id) {
            this.splice(item, 1);
            return true;
        }
    }
    return false;
}

This should do the trick, jsfiddle

这应该很管用,jsfiddle

#9


1  

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

If you are using jQuery, use jQuery.grep like this:

如果您正在使用jQuery,请使用jQuery。grep这样的:

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

Using ES5 Array.prototype.filter:

使用ES5 Array.prototype.filter:

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

#10


0  

Make sure you coerce the object id to an integer if you test for strict equality:

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

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

Demo

演示

#11


0  

If you are using underscore js, it is easy to remove object based on key. http://underscorejs.org. Example:

如果您正在使用下划线js,那么很容易基于key删除对象。http://underscorejs.org。例子:

  var temp1=[{id:1,name:"safeer"},  //temp array
             {id:2,name:"jon"},
             {id:3,name:"James"},
             {id:4,name:"deepak"},
             {id:5,name:"ajmal"}];

  var id = _.pluck(temp1,'id'); //get id array from temp1
  var ids=[2,5,10];             //ids to be removed
  var bool_ids=[];
  _.each(ids,function(val){
     bool_ids[val]=true;
  });
  _.filter(temp1,function(val){
     return !bool_ids[val.id];
  });