Alex Hunter
Alex Hunter

Reputation: 260

How to delete an entire javascript object?

i have this array:

const hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}]

Looping through i want to delete object where name is Skate

  for (const iterator of hobbies) {
    if(iterator === 'Skate'){
      delete object
    }
  }

Turns out, i think we cant delete a object literally, any idea on how to do this?

Upvotes: 0

Views: 94

Answers (3)

Quentin
Quentin

Reputation: 943564

JavaScript provides no mechanisms to explicitly delete objects.

You have to do it by deleting all references to the object instead. This will make it as eligible for garbage collection and it will be deleted when the garbage collector next does a sweep.

Since the only reference, in this example, to the object is as a member of an array you can remove it using splice.

const hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}]
const index_of_skate = hobbies.findIndex( object => object.name === 'Skate' );
hobbies.splice(index_of_skate, 1);
console.log(hobbies);

Upvotes: 3

Two Horses
Two Horses

Reputation: 1692

The simplest way to do that is to use the filter method on an array:

let hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}]
hobbies = hobbies.filter(hobby => hobby.name !== 'Skate')

Just make sure to assign hobbies to the filtered array (like i did) since it doesn't modify the original array.

Upvotes: 1

0stone0
0stone0

Reputation: 43973

A simple filter() would do the job:

let hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}]
hobbies = hobbies.filter((o) => o.name !== 'Skate');
console.log(hobbies);

Upvotes: 1

Related Questions