Remove Property from all Objects in Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove Property from all Objects in Array #

To remove a property from all objects in an array:

  1. Use the Array.forEach() method to iterate over the array.
  2. On each iteration, use the delete operator to delete the specific property.
  3. The property will get removed from all objects in the array.
index.js
const arr = [ {id: 1, name: 'Tom', test: 'abc'}, {id: 2, name: 'Bob', test: 'xyz'}, ]; arr.forEach(object => { delete object['test']; }); // 👇️ [{id: 1, name: 'Tom'}, {id: 2, name: 'Bob'}] console.log(arr);

The function we passed to the Array.forEach method gets called with each element (object) in the array.

We used the delete operator to delete a test property from each object.

The delete operator is used to remove a property from an object.

An alternative approach is to use the map() method with the rest operator.

To remove a property from all objects in an array:

  1. Use the Array.map() method to iterate over the array.
  2. Use destructuring assignment to extract the property to be removed.
  3. Return the rest of the properties from the map() method.
index.js
const arr = [ {id: 1, name: 'Tom', test: 'abc'}, {id: 2, name: 'Bob', test: 'xyz'}, ]; const newArr = arr.map(({test, ...rest}) => { return rest; }); // 👇️ [{id: 1, name: 'Tom'}, {id: 2, name: 'Bob'}] console.log(newArr);

The function we passed to the Array.map method gets invoked with each element in the array.

We destructured the test property from each object and used the rest operator (...) to get the rest of the object's properties.

We returned the rest of the object's properties from the function, practically excluding the test property.

The map() method does not change the contents of the original array, it returns a new array.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.