I have an JavaScript object like this:
id="1";
name = "serdar";
and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:
obj[1].remove();
I have an JavaScript object like this:
id="1";
name = "serdar";
and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:
obj[1].remove();
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: http://stackoverflow.com/questions/500606/javascript-array-delete-elements 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
.
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"]
Well splice works:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
Do NOT use the delete 'delete' operator on Arrays.
But maybe you want something like this?
var removeByAttr = function(arr, attr, value){
var i = arr.length;
while(i--){
if(arr[i] && arr[i][attr] && (arguments.length > 2 && arr[i][attr] === value )){
arr.splice(i,1);
}
}
return arr;
}
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'}]
Just an example.
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