-1

I'm pretty new to JavaScript/AngularJS, I would like to delete an object in an object.

Let's take this for example:

var heroes = {
  0: { 
      name: 'Batman',
      gender: 'M'
  },
  1: {
      name: 'Superman',
      gender: 'M'
  },
  3: {
      name: 'Catwoman',
      gender: 'F'
  }
};

I would like to delete the object when gender == 'F'.

for(var hero of heroes) {
    if(hero.gender == 'F') {
        //Delete her
    }
}

delete hero does not work, I have:

SyntaxError: applying the 'delete' operator to an unqualified name is deprecated

  • Please use the search before you ask a new question: [`[javascript] remove property`](https://stackoverflow.com/search?q=%5Bjavascript%5D+remove+property). – Felix Kling May 31 '16 at 14:20
  • 1
    Are you sure you have a `for...of` loop? They don't work with objects by default. Use `for...in`. – Felix Kling May 31 '16 at 14:23
  • 1
    Nothing like an edit that changes the question from what was originally asked. – epascarello May 31 '16 at 14:23
  • My `for...of` seems to work. The problem came on `delete hero;`. So, maybe am I iterating on an array of objects? :/ –  May 31 '16 at 14:33
  • 1
    *"maybe am I iterating on an array of objects"* Well, you should know better than us :P If that's the case then it's a duplicate of [remove objects from array by object property](http://stackoverflow.com/q/16491758/218196) – Felix Kling May 31 '16 at 14:45

3 Answers3

0

Use the delete operator

delete heroes[3]

If you do not know the key:

Object.keys(heroes).forEach( function (key) { //loop over the keys
    if (heroes[key].name==="Catwoman") {      //compare the name
        delete heroes[key];                   //remove the entry
    } 
} );
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Use delete operator.

The delete operator removes a property from an object.

delete heroes['3'];
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
delete heroes[3];

Use above code

Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20