DEV Community

Fatimah for Summitech Computing Ltd

Posted on

Mass delete properties from a Javascript object

Suppose you had an object like this:

const person = {name: 'Obama', age: 58, occupation: 'Statesperson', country: 'America', gender: 'male', marital_status: 'married'};

and you'd like to delete the following properties: marital_status, occupation and gender.

What you'd probably do (but hate) is:

delete person.marital_status;
delete person.occupation;
delete person.gender;

This is obviously tedious. A better way will be to use ES6's destructuring syntax:

const {marital_status, gender, occupation, ...others} = person;

console logging "others" will give you the person object without marital_status, occupation and gender.

{name: 'Obama', age: 58, country: 'America'};

One cool thing to note is that the order of properties is not important, however, the new variable (in this case, others) must be at the end with the three ellipsis.

Top comments (0)