javascriptecmascript-2018

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


Solution

  • 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.