šŸ“™ Understanding Neuronal Networks presale is now open - 20% off discount!

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.

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

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