简体   繁体   中英

Delete a property from an object without creating a new one (No delete operateur)

With Lodash omit for example to remove properties of an object with this piece of code :

this.current.obj = omit(this.current.obj, ['sellerSupportWeb', 'sellerSupportAgency', 'sellerSupportAgent'])

But this will create another object this.current.obj , but in my case I need to keep the same object

You have an alternative solution ? But not the delete operator

You have an alternative solution ? But not the delete operator

Nope. Your choices are create a new object with only the properties you want, or use the delete operator to remove the property from the existing object (which may have a significant impact on property lookup performance, although whether that actually matters will depend on how often you're using that object's properties).

Okay, technically you could wrap a Proxy object around the original and use the has , ownKeys , get , etc. hooks to pretend the property doesn't exist. But you'd have to be accessing it through the proxy.

You can use lodash's _.unset() to remove a property from an object:

 var obj = { a: 1, b: 2, c: 3 }; _.unset(obj, 'a'); console.log(obj); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

No. There's no alternative solution. I would strongly advise to use pure functional approach: don't modify variables, but transform them and create new ones. If you need to keep the same object (the same memory allocation) then delete operator is your only option.

You can set the property to undefined, then when you try to access to it the result will be the same that if the property had not exists.

myObject = {
    myProp = 'myValue'
}

myObject.myProp = undefined;
console.log(myObject.myProp);
console.log(myObject.inexistentProp);

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