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.

1

3 Answers 3

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Fair point hmm but afaik I don't think there's a built in JS function that can delete multiple.
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];
});

1 Comment

ok, good to know - thanks!
0

**`

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

`**

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.