Remove Property from all Objects in Array in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 13 20212 min read

banner

Photo by Simon Maage

Remove Property from all Objects in Array #

To remove a property from all objects in an array:

  1. Use the forEach() method to iterate over the array.
  2. On each iteration use the delete operator to delete the specific property from the object.
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 pass to the Array.forEach method gets called with each element (object) in the array.

In the code snippet, we use 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. Call the map() method, passing it a function.
  2. In the function, use destructuring to extract the property to be removed and use the rest (...) operator to store the rest of the properties in a variable.
  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 pass to the Array.map method gets invoked with each element in the array.

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

We return 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee