How to Remove a Property from All Objects in an Array in JavaScript?
Last Updated :
11 Nov, 2024
Improve
To remove a property from all objects in an array in JavaScript, you can use the forEach()
method to iterate over each object in the array and use the delete
operator to remove the specified property.
Example:
const arrayOfObjects = [
{ name: "Alice", age: 25, city: "New York" },
{ name: "Bob", age: 30, city: "San Francisco" },
{ name: "Charlie", age: 35, city: "Los Angeles" }
];
// Remove the 'age' property from all objects
arrayOfObjects.forEach(obj => {
delete obj.age;
});
console.log(arrayOfObjects);
// Output:
// [
// { name: "Alice", city: "New York" },
// { name: "Bob", city: "San Francisco" },
// { name: "Charlie", city: "Los Angeles" }
// ]
Output
[ { name: 'Alice', city: 'New York' }, { name: 'Bob', city: 'San Francisco' }, { name: 'Charlie', city: 'Los Angeles' } ]
Explanation:
forEach()
Method:- The
forEach()
method iterates over each element in thearrayOfObjects
.
- The
delete
Operator:- The
delete
operator removes a property from an object. Here,delete obj.age
removes theage
property from each object in the array.
- The
Important Notes:
- Mutation of Original Array: The above method modifies the objects directly within the original array. If you want to avoid this, you can create a copy of the objects before removing the property.
- Checking for Property Existence: If you're unsure whether all objects have the specified property, you can check for its existence using
if (obj.hasOwnProperty('propertyName'))
.
Example with Optional Check:
const arrayOfObjects = [
{ name: "Alice", age: 25, city: "New York" },
{ name: "Bob", city: "San Francisco" }, // No 'age' property
{ name: "Charlie", age: 35, city: "Los Angeles" }
];
arrayOfObjects.forEach(obj => {
if ('age' in obj) {
delete obj.age;
}
});
console.log(arrayOfObjects);
// Output:
// [
// { name: "Alice", city: "New York" },
// { name: "Bob", city: "San Francisco" },
// { name: "Charlie", city: "Los Angeles" }
// ]
Output
[ { name: 'Alice', city: 'New York' }, { name: 'Bob', city: 'San Francisco' }, { name: 'Charlie', city: 'Los Angeles' } ]
This approach ensures that you only attempt to delete the property if it exists in the object.