Code repetition: deleting keywords to remove obj properties

Hi;
how can I delete more than 1 properties of an obj without repeting delete?


let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};

// change code below this line
delete foods.oranges;
delete foods.plums;
delete foods.strawberries;
// change code above this line

console.log(foods);

It can vary. One approach would be to use a loop to run thru a list of keys and have a delete on each key, e.g.,
you might hand a list (e.g., an array) of keys to a function that loops thru the values and removes those properties from the object. You still have multiple deletes but you’re not entering them one by one as above.

A quick Google search yields a number of questions and approaches on the subject, e.g., one way given on Stack Overflow is How to delete multiple properties from an Object using a single delete?

Stack Overflow is immensely useful over a range of subjects; I suggest checking it out further.

1 Like