3

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.

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I have used this already, but the element's position changes dynamically and I need to remove it dynamically too. This doesn't work in my situation. Thanks for the suggestion.
@AbhishekDhanrajShahdeo You can use the updated code for removing elements from an array where you don't know the index of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.