1

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?

Brad
  • 847
  • 1
  • 7
  • 20
  • Your fiddler has a typo!!!! – Leo Oct 31 '16 at 07:22
  • Thanks @Leo - fixed! – Brad Oct 31 '16 at 07:30
  • Your title says "delete element in object literal", yet you seem to actually to be trying to delete an object in an array. –  Oct 31 '16 at 08:20
  • @torazaburo you're absolutely correct. When I wrote the question, I thought I _was_ trying to delete an object literal. Turns out that was incorrect! I think I need to brush up on the difference again. – Brad Oct 31 '16 at 08:22

2 Answers2

2

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; }
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
  • Thanks! That works! I could have sworn that I had tried this already! Strangely through, when I run this code `console.log(activeCaseImplants); activeCaseImplants.implants.splice(1, 1); console.log(activeCaseImplants);` BOTH console logs display the object without the apples element... Weird! – Brad Oct 31 '16 at 07:26
  • What does the `.as-console-wrapper` do? – Brad Oct 31 '16 at 07:34
  • it looks more, like a console problem, which is out of time. the css makes the whole object viewable in the above window. – Nina Scholz Oct 31 '16 at 07:36
0

JSON.fruits.splice(1, 1); // to remove apples

Knowledge: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice