George Song

Remove Properties From JavaScript Objects

July 9, 2020

Use Case

You have a JavaScript object that you got from somewhere (e.g. retrieved from 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 onto the next part of the workflow.

Solution: Destructure/Rest Syntax

The combination of object destructuring and object literal spread/rest syntax to the rescue ⛑.

const { secretKeyLocation, ...rest } = restaurant;doSomethingWith(rest);

With this, you now have three variables:

  • secretKeyLocation with the value of "somewhere"

  • rest, a new object with the secretKeyLocation property removed:

    {
      name: "Nong's Khao Man Gai",
      address: "609 SE Ankeny St",
      phone: "503-740-2907",
    }

    It’s worth noting that rest can be whatever variable name you want, there’s nothing special about the name rest.

  • restaurant remains untouched and retains its original value. Immutability FTW 🙌!

👩‍💻 Try It Out