Remove Properties From JavaScript Objects
Use Case
Suppose you have a JavaScript object received from a source (e.g., retrieved from an API):
const restaurant = { name: "Nong's Khao Man Gai", address: "609 SE Ankeny St", phone: "503-740-2907", secretKeyLocation: "somewhere",};You want to remove secretKeyLocation before passing the object on to the next
part of the workflow.
Solution: Remove Property Using Destructuring + Rest Syntax
Use a combination of object destructuring and object literal spread/rest syntax.
const { secretKeyLocation, ...rest } = restaurant;doSomethingWith(rest);With this, you now have three variables:
-
secretKeyLocationwith the value of"somewhere" -
rest, a new object with thesecretKeyLocationproperty removed:{name: "Nong's Khao Man Gai",address: "609 SE Ankeny St",phone: "503-740-2907",}It’s worth noting that
restcan be any valid variable name; the namerestitself has no special meaning. -
restaurantremains untouched and retains its original value. Immutability FTW 🙌!
George Song