Abhishek Dhanraj Shahdeo
Abhishek Dhanraj Shahdeo

Reputation: 1356

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 situation I'm in to.

    {brands:[51,2046,53,67,64]}

Now, I have to remove 53 from this which I am calculating using some elements property, but I'm not able to remove the data and unable to find the solution for this situation. Please help me folks, thank you.

Upvotes: 3

Views: 138

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use Array.prototyp.splice,

var data = { 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;
var data = { 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);
}

var data = { brands:[51,2046,53,67,64] };
var removed = removeItem(data.brands,53);

Upvotes: 4

Related Questions