Delete multiple object properties?

后端 未结 9 951
天命终不由人
天命终不由人 2020-12-29 01:51

I create an object with multiple properties -

var objOpts = {
  option1: \'Option1\',
  option2: \'Option2\',
  option2: \'Option3\'
};

I t

9条回答
  •  伪装坚强ぢ
    2020-12-29 02:22

    I'm sure you are trying to add custom properties to an object.

    A simpler way I would suggest is by creating a sub property:

    objOpts.custom.option4 = 'Option4'
    objOpts.custom.option5 = 'Option5'
    

    this way you could delete objOpts.custom and get done with it. Note that after this step you would have to recreate objOpts.custom = {}.

    Moreover this way would also feel closer to OOP, since your public properties would easily be distinguishable from private ones.

    If you are beginning with deleting objects in JavaScript, I'd like to point to to an excellently written article on the topic: http://perfectionkills.com/understanding-delete/

    You could play around with the meta properties which allow you to protect properties from being deleted etc. (to create an even better coding flow for your case)

    EDIT:

    I'd like to add that instead of deleting and recreating the property, you could simply say objOpts.custom = {} which would release the option4 and option5 from memory (eventually, via Garbage Collection).

提交回复
热议问题