0

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?

asked Dec 16, 2020 at 12:13
3
  • Why do you want to delete it? Commented Dec 16, 2020 at 12:18
  • 1
    Probably a duplicate of stackoverflow.com/questions/9882284/… Commented Dec 16, 2020 at 12:19
  • i want to delete the entire object @Christian Commented Dec 16, 2020 at 12:21

3 Answers 3

3

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

Cid
15.3k4 gold badges33 silver badges49 bronze badges
answered Dec 16, 2020 at 12:18
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Dec 16, 2020 at 12:18

Comments

1

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.

answered Dec 16, 2020 at 12:19

1 Comment

be careful, hobbies is const. You can't re-assign it

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.