I have an object as follows :
let obj = {foo: 1, bar: 2, baz: 3}
I would like to delete a specific property by calling a method that takes as parameter the name of the property to delete
removeProperty(obj, propertyName) {
let { propertyName, _, ...result } = obj
return result
}
the problem is that this method only works when we write the name of the property directly in the syntax spead, like: let { bar, _, ...result } = obj
.But it does not work by passing it as a parameter, because the syntax spead creates it as a new variable
how can we do that, with another solution if possible except the omit
of lodash
You can use computed properties in destructuring:
let obj = {foo: 1, bar: 2, baz: 3}
function removeProperty(obj, propertyName) {
let { [propertyName]: _, ...result } = obj
return result
}
console.log(removeProperty(obj, 'foo'));
This will assign the property with the name of the value propertyName
to a throwaway variable and essentially remove that key. See the MDN documentation.
Another alternative to destructuring
would be to use delete
. The following solution reduces time-complexity by about 35% compared to destructuring
(in Desktop Chrome)
let obj = {foo: 1, bar: 2, baz: 3}
function removeProperty(obj, propertyName) {
let newObj = {...obj};
delete newObj[propertyName];
return newObj;
}
console.log(removeProperty(obj, 'foo'));
https://jsperf.com/so53753276
The results vary depending upon the browser used. The results are rather intriguing. Desktop Safari destructuring
outperforms delete
, but Desktop Chrome out performs all numbers from Desktop Safari.
+-----------------------------------+
| Browser | delete | destructure |
+---------+-----------+-------------+
| Chrome | 3,229,791 | 1,993,256 |
| Safari | 1,186,679 | 1,872,396 |
+---------+-----------+-------------+
The results on iOS are less surprising, as Chrome is just really Safari under the hood.
+-----------------------------------+
| Browser | delete | destructure |
+---------+-----------+-------------+
| Chrome | 1,146,496 | 1,785,551 |
| Safari | 1,182,067 | 1,793,772 |
+---------+-----------+-------------+
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With