Delete multiple object properties?

大兔子大兔子 提交于 2020-11-25 20:07:03

问题


I create an object with multiple properties -

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

I then add some more properties later on -

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

I'm then done with the two latter created properties ('Option4' & 'Option5') and I want to clear/delete both.

Currently I'd do it like so -

delete objOpts.option4
delete objOpts.option5

Is there another way to go about doing this? Imagine I'd added 5 more properties and needed to clear/delete them all that'd be five lines of almost identical 'delete' code


回答1:


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




回答2:


ES6 provides an elegant solution to this: Rest in Object Destructuring:

let { a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 };
console.log(rest); // { c: 30, d: 40 }

Note that this doesn't mutate the original object, but some folks might still find this useful.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment




回答3:


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




回答4:


One way is to create a separate function which takes your object and properties as argument.

Js fiddle example

Code also below:

var objOpts = {
  option1: 'Option1',
  option2: 'Option2',
  option3: 'Option3',
  option4: 'Option4'
};

/** 
 * Method for removing object properties
 *
 */
var removeObjectProperties = function(obj, props) {

    for(var i = 0; i < props.length; i++) {
        if(obj.hasOwnProperty(props[i])) {
            delete obj[props[i]];
        }
    }

};

// remove
removeObjectProperties(objOpts, ["option1", "option2"]);

// objOpts - after
console.log(objOpts);



回答5:


I would also supply a more modern method than Mauno Vänä:

function deleteProps (obj, prop) {
    for (const p of prop) {
        (p in obj) && (delete obj[p]);
    }    
}

Example:

// Create sample object
const myObject = {
    a: 'Foo',
    b: 'Baa',
    c: 'Oof'
};

// Prints: {a: "Foo", b: "Baa", c: "Oof"}
console.log(myObject);

// Delete props
deleteProps(myObject, ['a', 'b']);

// Prints: {c: "Oof"}
console.log(myObject);



回答6:


One aditionnal otpion would be to use Object.assign to set the properties to either null or undefined depending on your use case. This does not delete the properties but clears them. So you would do either of these :

// Modify the object directly
Object.assign(objOpts, {option4: null, option5: null});

OR

// Create a copy of the object with the properties cleared 
const newObject = Object.assign({}, objOpts, {option4: null, option5: null});

You could also use an array to list the properties to clear with Array.reduce() to create the last param of Object.assign().




回答7:


var obj = {"key1":1,"key2":2,"key3":3,"key4":4};

if (!('multidelete' in Object.prototype)) {
Object.defineProperty(Object.prototype, 'multidelete', {
    value: function () {
        for (var i = 0; i < arguments.length; i++) {
            delete this[arguments[i]];
        }
    }
});
}

obj.multidelete("key1","key3");

You can use it like this to delete multiple keys in object




回答8:


var extraOpts = {}
extraOpts.options = ['option4','option5','option6','option7','option8']
delete extraOpts.options
console.log(extraOpts.options)



回答9:


Object.keys(object).forEach((prop) => delete object[prop]);


来源:https://stackoverflow.com/questions/24864613/delete-multiple-object-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!