Find and remove objects in an array based on a key value in JavaScript
JavascriptJqueryArraysObjectJavascript Problem Overview
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.
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;
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 the following?
Data:
[ {"id":"99", "name":"Have fun boys and girls"}, {"id":"108", "name":"You are awesome!"}]
Javascript Solutions
Solution 1 - Javascript
Here is a solution if you are not using jQuery:
myArray = myArray.filter(function( obj ) {
return obj.id !== id;
});
Solution 2 - Javascript
> I can grep the array for the id, but how can I delete the entire object where id == 88
Simply filter by the opposite predicate:
var data = $.grep(data, function(e){
return e.id != id;
});
Solution 3 - Javascript
You can simplify this, and there isn't really any need for using jQuery here.
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.
Solution 4 - Javascript
There's a new method to do this in ES6/2015 using findIndex and the array spread operator:
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 ? [
...array.slice(0, index),
...array.slice(index + 1)
] : array;
}
This way, you can 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.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!");
Solution 5 - Javascript
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:
items = $.grep(items, function(item) {
return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]
Using ES5 Array.prototype.filter:
items = items.filter(function(item) {
return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]
Solution 6 - Javascript
Assuming that ids are unique and you'll only have to remove the one element splice
should do the trick:
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);
Solution 7 - Javascript
Native ES6 solution:
const pos = data.findIndex(el => el.id === ID_TO_REMOVE);
if (pos >= 0)
data.splice(pos, 1);
If you know that the element is in the array for sure:
data.splice(data.findIndex(el => el.id === ID_TO_REMOVE), 1);
Prototype:
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/
Note: this removes the item in-place. If you need a new array, use filter
as mentioned in previous answers.
Solution 8 - Javascript
const data = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
Here we get the index of the object whose value of the id is "88"
const index = data.findIndex(item => item.id === "88");
console.log(index); // 0
We use splice function to remove the specified object from data array
data.splice(index,1);
console.log(data); // [{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}]
Solution 9 - Javascript
Maybe you are looking for $.grep()
function:
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
});
Solution 10 - Javascript
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
Solution 11 - Javascript
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.
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.
Solution 12 - Javascript
I agree with the previous answers. A simple way if you want to find an object by id and remove it is simply like the below code:
var obj = JSON.parse(data);
var newObj = obj.filter(item => item.Id != 88);
Solution 13 - Javascript
Make sure you coerce the object id to an integer if you test for strict equality:
var result = $.grep(data, function(e, i) {
return +e.id !== id;
});
Solution 14 - Javascript
If you are using Underscore.js, it is easy to remove an object based on a key.
Example:
var temp1=[{id:1,name:"safeer"}, // Temporary 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];
});