How do I remove an object from an array with JavaScript? [duplicate]
I have an JavaScript object like this:
id="1";
name = "serdar";
and I have an Array which contains many objects of above. How ca开发者_如何学Pythonn I remove an object from that array such as like that:
obj[1].remove();
Well splice
works:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
Do NOT use the delete
operator on Arrays. delete
will not remove an entry from an Array, it will simply replace it with undefined
.
var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]
But maybe you want something like this?
var removeByAttr = function(arr, attr, value){
var i = arr.length;
while(i--){
if( arr[i]
&& arr[i].hasOwnProperty(attr)
&& (arguments.length > 2 && arr[i][attr] === value ) ){
arr.splice(i,1);
}
}
return arr;
}
Just an example below.
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]
removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]
If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:
const people = [
{ id: 1, name: 'serdar' },
{ id: 5, name: 'alex' },
{ id: 300, name: 'brittany' }
];
const idToRemove = 5;
const filteredPeople = people.filter((item) => item.id !== idToRemove);
// [
// { id: 1, name: 'serdar' },
// { id: 300, name: 'brittany' }
// [
Watch out though, filter()
is non-mutating, so you'll get a new array back.
See the Mozilla Developer Network notes on Filter.
Cleanest and fastest way (ES6)
const apps = [
{id:1, name:'Jon'},
{id:2, name:'Dave'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
apps.splice(apps.findIndex(a => a.id === itemToBeRemoved.id) , 1)
//print result
console.log(apps)
Update: if any chance item doesn't exist in the look up array please use below solution, updated based on MaxZoom's comment
const apps = [
{id:1, name:'Jon'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
const findIndex = apps.findIndex(a => a.id === itemToBeRemoved.id)
findIndex !== -1 && apps.splice(findIndex , 1)
//print result
console.log(apps)
You can use either the splice()
method or the delete
operator.
The main difference is that when you delete an array element using the delete
operator, the length of the array is not affected, even if you delete the last element of the array. On the other hand, the splice()
method shifts all the elements such that no holes remain in the place of the deleted element.
Example using the delete
operator:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
if (3 in trees) {
// this does not get executed
}
console.log(trees.length); // 5
console.log(trees); // ["redwood", "bay", "cedar", undefined, "maple"]
Example using the splice()
method:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees.splice(3, 1);
console.log(trees.length); // 4
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
I use this quite a bit so I created a small prototype. Simply looks for the item then pulls it out if there is a match.
//Prototype to remove object from array, removes first
//matching object only
Array.prototype.remove = function (v) {
if (this.indexOf(v) != -1) {
this.splice(this.indexOf(v), 1);
return true;
}
return false;
}
Can be called like:
var arr = [12, 34, 56];
arr.remove(34);
The result would be [12, 56]
Has a boolean return if there was a successful remove, false if the element didn't exist.
If you know the index that the object has within the array then you can use splice(), as others have mentioned, ie:
var removedObject = myArray.splice(index,1);
removedObject = null;
If you don't know the index then you need to search the array for it, ie:
for (var n = 0 ; n < myArray.length ; n++) {
if (myArray[n].name == 'serdar') {
var removedObject = myArray.splice(n,1);
removedObject = null;
break;
}
}
Marcelo
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
var ind = arr.findIndex(function(element){
return element.id===2;
})
if(ind!==-1){
arr.splice(ind, 1)
}
console.log (arr)
Please note that findIndex method is not supported in Internet Explorer but polyfill can be used from here
var user = [
{ id: 1, name: 'Siddhu' },
{ id: 2, name: 'Siddhartha' },
{ id: 3, name: 'Tiwary' }
];
var recToRemove={ id: 1, name: 'Siddhu' };
user.splice(user.indexOf(recToRemove),1)
//K.I.S.S. method
//(the setup/comments is/are longer than the code)
//cards is a two dimensional array object
// has an array object with 4 elements at each first dimensional index
//var cards = new Array()
//cards[cards.length] = new Array(name, colors, cost, type)
//Can be constructed with Associated arrays, modify code as needed.
//my test array has 60 'cards' in it
// 15 'cards' repeated 4 times each
// groups were not sorted prior to execution
// (I had 4 groups starting with 'U' before the first 'A')
//Should work with any dimensionality as long as first
//index controls sort order
//sort and remove duplicates
//Algorithm:
// While same name side by side, remove higher entry;
// assumes 'cards' with same name have same other data
// (otherwise use cards[i-1] === cards[i] to compare array objects).
//Tested on IE9 and FireFox (multiple version #s from 31 up).
//Also tested by importing array data from 5MB text file.
//Quick execution
cards.sort()
for (i=1; i<cards.length-1; i++){
while (cards[i-1][0] == cards[i][0]){
cards.splice(i,1)
}
}
we have an array of objects, we want to remove one object using only the id property
var apps = [
{id:34,name:'My App',another:'thing'},
{id:37,name:'My New App',another:'things'
}];
get the index of the object with id:37
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);
// remove object
apps.splice(removeIndex, 1);
Use the splice method.
(At least I assume that is the answer, you say you have an object, but the code you give just creates two variables, and there is no sign of how the Array is created)
Use delete-keyword.
delete obj[1];
EDIT: see: Deleting array elements in JavaScript - delete vs splice delete will undefine the offset but not completly remove the entry. Splice would be correct like David said.
delete obj[1];
Note that this will not change array indices. Any array members you delete will remain as "slots" that contain undefined
.
var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];
// get index of object with id:37
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);
// remove object
apps.splice(removeIndex, 1);
If it's the last item in the array, you can do obj.pop()
精彩评论