Search code examples
javascriptjsonobject-literal

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"
    }
]};

console.log(JSON);
delete JSON.fruits[1];
console.log(JSON);

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 null which breaks my script.

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

Any ideas?


Solution

  • 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);
    console.log(object);
    .as-console-wrapper { max-height: 100% !important; top: 0; }