Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to remove a property from an object

Short answer

The delete operator removes a property from the object itself:

const user = { name: 'Anna', password: 'secret' };
delete user.password;
 
console.log(user);

Output:

{
  "name": "Anna"
}

A copy without the property

Destructuring with ...rest takes the property out and leaves the rest in a new object. The original does not change:

const user = { name: 'Anna', password: 'secret', age: 30 };
const { password, ...safeUser } = user;
 
console.log(JSON.stringify(safeUser));
console.log(Object.keys(user).length);

Output:

{"name":"Anna","age":30}
3

Several properties

Filter the pairs of the object by a list of keys:

const omit = (object, keys) => Object.fromEntries(Object.entries(object).filter(([key]) => !keys.includes(key)));
 
const order = { id: 5, total: 40, internalNote: 'vip', token: 'abc' };
 
console.log(JSON.stringify(omit(order, ['internalNote', 'token'])));

Output:

{"id":5,"total":40}

Common mistake

Setting a property to undefined does not remove it: the key stays in the object:

const user = { name: 'Anna', password: 'secret' };
user.password = undefined;
 
console.log(Object.keys(user).join(', '));
console.log('password' in user);

Output:

name, password
true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.