Mouad Ennaciri
Mouad Ennaciri

Reputation: 1279

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

Upvotes: 4

Views: 165

Answers (4)

Ori Drori
Ori Drori

Reputation: 193130

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>

Upvotes: 2

viltor
viltor

Reputation: 341

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075615

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.

Upvotes: 2

lukaleli
lukaleli

Reputation: 3625

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.

Upvotes: 1

Related Questions