Deleting An Element From Json In Javascript/jquery
I have a problem in deleting data from a JSON object in javascript. I'm creating this JSON dynamically and the removal shall also take place dynamically. Below is my JSON and the s
Solution 1:
Try to use Array.prototyp.splice
,
vardata = { brands:[51,2046,53,67,64] };
data.brands.splice(2,1);
Since you want to remove an element
from an array
inside of a simple object
. And splice
will return an array of removed elements.
If you do not know the position of the element going to be removed, then use .indexOf()
to find the index of the dynamic element,
var elementTobeRemoved = 53;
vardata = { brands:[51,2046,53,67,64] };
var target = data.brands;
target.splice(target.indexOf(elementTobeRemoved),1);
You could write the same thing as a function like below,
function removeItem(arr,element){
return arr.splice(arr.indexOf(element),1);
}
vardata = { brands:[51,2046,53,67,64] };
var removed = removeItem(data.brands,53);
Post a Comment for "Deleting An Element From Json In Javascript/jquery"