1

I have an array of objects which is looped and then deleting a set of key and values from it.I would like to know how to delete a set of keys with a single line if code instead of writing each delete for every key.

for (var i = 0; i < oldWorkers.length; i++) {
    delete oldWorkers[i].$$hashKey;
    delete oldWorkers[i].location;
    delete oldWorkers[i].name;
    delete oldWorkers[i].mobile_no;
    delete oldWorkers[i].type;
    LoadEntries.saveDaybook(oldWorkers[i]).then(
      function (resp) {
        proms.push(resp);
      },
      function (err) {
        CommonService.hideLoader();
        CommonService.toast(err);
      }
    );
  }
5
  • you can make a generic function to delete elements Commented Feb 26, 2018 at 12:03
  • check this stackoverflow.com/questions/32534602/… Commented Feb 26, 2018 at 12:03
  • you could re-group those value as a sub-object of oldWorkers[i] so you would just need to delete the sub-object itself. Commented Feb 26, 2018 at 12:04
  • ["$$hashKey","location","name","mobile_no","type"].forEach(key => { delete oldWorkers[i][key] }) Commented Feb 26, 2018 at 12:06
  • loop throgh the array and splice by index for eg : for(var i=0;i<data.length;i++){ data.splice(i)} Commented Feb 26, 2018 at 12:09

2 Answers 2

6

You can loop through keys and delete inside the callback

["$$hashKey", "location", "name", ".mobile_no", "type"].forEach(el => {delete oldWorkers[i][el];} )
Sign up to request clarification or add additional context in comments.

2 Comments

I actually prefer your answer due to the nice ECMA6 syntax :)
I'm not the OP :) I'm the guy who did the accepted answer. But I've +1'd yours.
2

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

Declare a runtime array and iterate over it, perhaps.

['$$hashKey', 'location', 'name', 'mobile_no', 'type'].forEach(function(key) {
    delete oldWorkers[i][key];
});

1 Comment

How do I write something for deleting keys other than a list of keys?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.