0

I was wondering if it is somehow possible to delete multiple object properties with a one-liner in React?

I know about the delete-command: delete obj.property but since I'm deleting multiple numbers of object properties it would be nice to do this on one line instead of writing each time delete obj.property for every object that I'd like to delete.

Pascal
  • 77
  • 1
  • 11
  • asking for functions: https://stackoverflow.com/questions/32534602/javascript-built-in-function-to-delete-multiple-keys-in-an-object – ford04 Nov 10 '20 at 11:41

3 Answers3

3

I mean you can create some helper function if its gonna be reuse throughout the code

function deleteProperties(target, properties){
   properties.forEach(item=>{
      delete target[item];
   })

}

const obj = {
option1: "KL",
option2: "AB",
option3: "CD"
}

deleteProperties(obj, ["option1", "option2"]);

console.log(obj)

Fiddle here : https://jsfiddle.net/L1csragx/

or

["option1","option2"].forEach(item=> delete obj[item]);
keysl
  • 2,127
  • 1
  • 12
  • 16
  • Yes indeed, that was the other solution I was considering. I was just wondering whether there is a way to delete those object properties by using something a long the way of `delete obj["option1", "option2"]`. Would make it a lot easier and more parsimonious. – Pascal Nov 10 '20 at 11:21
  • 1
    Fair point hmm but afaik I don't think there's a built in JS function that can delete multiple. – keysl Nov 10 '20 at 11:23
1

You can't delete multiple properties via one statement, so some sort of iteration is required one way or another. for example

['delete_key_1', 'delete_key_2'].forEach(function(key) {
    delete myObject[key];
});
sazzad
  • 505
  • 4
  • 5
0

**`

const objec = {
option1: "KL",
option2: "AB",
option3: "CD"
}
let deleteingProp = ["option1","option2"]
for(let i of deleteingProp){
  delete objec[i]
}

`**

LOVENEET SINGH
  • 193
  • 2
  • 9