简体   繁体   中英

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?

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);

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM