Remove properties from a JavaScript Object

In this post, we'll see how to remove properties from a JavaScript Object using the delete operator and the object destructuring.

First things first. What is an object in JavaScript?

An object in JavaScript is a collection of properties. A property is a key-value pair that contains a name and a value.

In fact, objects in JavaScript can be compared to objects in real life.

const car = {
  name: 'BMW',
  model: '320i',
  year: 2012
};

In this example, we have created a car object with three properties: name, model, and year.

Let's suppose we want to remove the property year from the car object. How can we do that?

We can remove a property or multiple properties from an object in JavaScript by using the delete operator or the object destructuring.

1. delete operator

In JavaScript the delete operator removes a property from an object;

Remove a single property

const car = {
  name: 'BMW',
  model: '320i',
  year: 2012
};

console.log(car); 
// { name: 'BMW', model: '320i', year: 2012 }

delete car.year;

console.log(car); 
// { name: 'BMW', model: '320i' }

Remove multiple properties

To remove multiple properties we can iterate throw an array of keys that we want to delete from the object. In this example, we'll use the forEarch method.

const car = {
  name: 'BMW',
  model: '320i',
  year: 2012
};

console.log(car); 
// { name: 'BMW', model: '320i', year: 2012 }

const removeKeys = ['model', 'year'];

removeKeys.forEach((item) => delete query[item]);

console.log(car);
// { name: 'BMW' }

Keep in mind that by using the delete operator we end up mutating the original object.

2. Object Destructuring

The object destructuring makes it possible to unpack properties from objects, into distinct variables.

Remove a known property

const car = {
  name: 'BMW',
  model: '320i',
  year: 2012
};

console.log(car); 
// { name: 'BMW', model: '320i', year: 2012 }

const { year, ...rest } = car;

console.log(year); 
// 2012

console.log(rest); 
// { name: 'BMW', model: '320i' }

Remove a dynamic property

In the example above we have seen how to remove a known property from an object.

How about having a dynamic property? In the example below, we'll see how to do that as well.

const car = {
  name: 'BMW',
  model: '320i',
  year: 2012
};

console.log(car); 
// { name: 'BMW', model: '320i', year: 2012 }

// let's suppose this is a dynamic property
const removeKey = 'year';

const { [removeKey]: remove, ...rest } = car;

console.log(remove); 
// 2012

console.log(rest); 
// { name: 'BMW', model: '320i' }

Unlike the delete operator the object destructuring instead of mutating the original object creates a new one.