Javascript clone new object without one or more properties

In order to create a clone of a Javascript object while excluding a set of attributes we can use the following formula:

const {prop1, prop2, propN, ...newObj} = ingredients

Let's say we have the the following Javascript object:

const ingredients = {
    apples: '🍎', 
    chicken: '🍗',
    bread: '🥖',
    broccoli: '🥦', 
    milk: '🥛'
}

If we want to create a new object noMeat, while excluding the chicken property from the initial object we can do:

const {chicken, ...noMeat} = ingredients

Javascript clone new object without one or more properties

And it will work also with multiple excluded properties:

const {milk, chicken, ...vegetarian} = ingredients

Using the spread operator and the destructing statement is a shorthand for writing somethig like this:

const vegetarian = Object.assign({}, ingredients);
delete vegetarian.milk;
delete vegetarian.chicken;

The full code is here and the live example is on GitHub pages.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X