Delete multiple object properties?

后端 未结 9 968
天命终不由人
天命终不由人 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

    There is one simple fix using the library lodash.

    The _.omit function takes your object and an array of keys that you want to remove and returns a new object with all the properties of the original object except those mentioned in the array.

    This is a neat way of removing keys as using this you get a new object and the original object remains untouched. This avoids the problem of mutation where if we removed the keys in the original object all the other parts of code using that object might have a tendency to break or introduce bugs in the code.

    Example

    var obj = {x:1, y:2, z:3};
    var result = _.omit(obj, ['x','y']);
    console.log(result);
    
    //Output
    result = {z:3};
    

    Link for the documentation of the same Click Here

    0 讨论(0)
  • 2020-12-29 02:22
    Object.keys(object).forEach((prop) => delete object[prop]);
    
    0 讨论(0)
  • 2020-12-29 02:25
    var extraOpts = {}
    extraOpts.options = ['option4','option5','option6','option7','option8']
    delete extraOpts.options
    console.log(extraOpts.options)
    
    0 讨论(0)
提交回复
热议问题