To remove a specific property from an object in JavaScript, you can use the delete
operator or create a new object without those properties. Let’s explore some approaches :
Using the delete Operator
This method directly removes properties from the original object.
const obj = {
name: 'Josh',
age: 30,
city: 'New York'
};
// Remove the 'age' property
delete obj.age;
console.log(obj); // Output: { name: 'Josh', city: 'New York' }
Using Object Destructuring
const obj = {
name: 'Josh',
age: 30,
city: 'New York'
};
// Destructure and create a new object without 'age'
const { age, ...newObj } = obj;
console.log(newObj); // Output: { name: 'Josh', city: 'New York' }
Using Object.keys() and reduce()
You can filter out unwanted properties and create a new object.
const obj = {
name: 'Josh',
age: 30,
city: 'New York'
};
const propertiesToRemove = ['age'];
const newObj = Object.keys(obj).reduce((acc, key) => {
if (!propertiesToRemove.includes(key)) {
acc[key] = obj[key];
}
return acc;
}, {});
console.log(newObj); // Output: { name: 'Josh', city: 'New York' }