JavaScript - spread and rest syntax to remove specific property from object
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.
values = {
id: 1,
name: 'hello world',
vehicle: 'car',
time: '3.30 pm',
date: '02 MAR 1990',
};
const { time, date, ...rest } = values;
now ***...rest*** contains the object values of {
id: 1,
name: 'hello world',
vehicle: 'car',
};
Another alternative to destructuring
would be to use delete
. The following solution reduces time-complexity by about 35% compared to destructuring
(in Desktop Chrome)
Solution
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'));
Performance Test
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 |
+---------+-----------+-------------+
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete