I'm initializing an array with dynamic objects and result is following
var arr = [
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0}
];
now i want to remove any object from this array but not finding proper solution. Can someone please help me how to do it.
4 Answers 4
i want to remove any object from this array but not finding proper solution
You can use splice method, It accepts the index(start) of the to be removed element and also the deleteCount that is number of elements to be removed from the starting index
var arr = [{
id: "1",
name: "A",
quantity: 1
},
{
id: "2",
name: "B",
quantity: 2
},
{
id: "3",
name: "C",
quantity: 3
},
{
id: "4",
name: "D",
quantity: 4
}
];
arr.splice(1, 1)
console.log(arr)
Comments
at the beginning you must know which object you want to delete it (for example the object whose id = x)
then you can use this code
arr = arr.filter(function(e){ return e.id != x });
Comments
Guys thank you so much for your help. I have found solution to this issue, following is what I wanted.
this is my array with initial values set.
var arr = [
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0}
];
and I I can remove any object like this:
arr.splice(arr[index], 1);
Comments
The solution is that filter your arr Array which has non-empty values like this-:
var arr = [
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0},
{id: "", name: "", quantity: 0}
];
arr = arr.filter((obj)=>obj.id!==''); // you can use any field to filter
arr = arr.filter((obj)=>obj.id!=='' || obj.name!=='');// multiple fields to filter
Now your arr variable will be updated with new array of objects with non-empty fields
arr=[].