Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - spread and rest syntax to remove specific property from object

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

like image 856
Mouad Ennaciri Avatar asked Dec 13 '18 00:12

Mouad Ennaciri


2 Answers

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.

like image 68
Andrew Li Avatar answered Oct 08 '22 21:10

Andrew Li


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

like image 24
AnonymousSB Avatar answered Oct 08 '22 19:10

AnonymousSB