Brad Brad - 1 year ago 72
Javascript Question

Can't seem to delete element in object literal

I have a JSON object literal from which I'm trying to delete an element (let's say apples). I've tried many things, but I just can't seem to get it to work.

var JSON = {
"fruits": [{
"name": "oranges",
"quantity": "3"
"name": "apples",
"quantity": "2"
"name": "bananas",
"quantity": "3"

delete JSON.fruits[1];

Calling the above code results in the object being removed, but it looks like then inserts the key before the 3rd object. Have a look at this fiddle. I don't want that to happen.

That's what happens in the Fiddle. But then in my live script however, it looks like it replaces the deleted object with the word
which breaks my script.

I've also tried many variations of
but that seems to be for arrays, rather than object literals.

Any ideas?

Answer Source

You could use Array#splice for the array inside of the object.

delete deletes the object, but you get an undefined element of the array.

var object = { fruits: [{ name: "oranges", quantity: "3" }, { name: "apples", quantity: "2" }, { name: "bananas", quantity: "3" }] };

object.fruits.splice(1, 1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download