Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple properties from an Object using a single delete?

I have the following object:

var myArr = {one:'1',two:'2',three:'3',four:'4',five:'5'};

I want to delete three properties from that object at once like:

delete myArr[one, three, five];

and it is failing. Do I have to perform an independent delete for each property like so:

delete myArr[one]; delete myArr[three]; delete myArr[five];

Thank you.

like image 513
NetizenKing Avatar asked Nov 25 '16 13:11

NetizenKing


1 Answers

You could use an array for the keys and iterate for deleting.

var object = { one: '1', two: '2', three: '3', four: '4', five: '5' };

['one', 'three', 'five'].forEach(function (k) {
    delete object[k];
});

console.log(object);

With Reflect.deleteProperty

var object = { one: '1', two: '2', three: '3', four: '4', five: '5' };

['one', 'three', 'five'].forEach(Reflect.deleteProperty.bind(null, object));

console.log(object);
like image 58
Nina Scholz Avatar answered Oct 18 '22 08:10

Nina Scholz