One liner to delete multiple object properties

All we need is an easy explanation of the problem, so here it is.

I have a few object properties I need to delete at certain point but I still need others so I can’t just write delete vm.model; to remove all of it.

At the moment there are 5 properties I need to delete but the list will most likely grow so I don’t want to end up with.

delete vm.model.$$hashKey;
delete vm.model.expiryDate;
delete vm.model.sentDate;
delete vm.model.startDate;
delete vm.model.copied;

I’m looking for a one liner that will do it for me. I did some research and found the _.omit lodash function but I don’t want to end up downloading whole library just for a single function.

Is there a angularjs/js function that will clear multiple properties at once?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

There is no native function that does this yet; but you can always just loop and delete:

const obj = {
  prop1: 'foo',
  prop2: 'bar',
  prop3: 'baz'
}

;[ 'prop1', 'prop2' ].forEach(prop => delete obj[prop])

console.log(obj)
    

… found the _.omit lodash function but I don’t want to end up downloading whole library just for a single function.

Just abstract the same concept into a function and reuse it:

const obj = {
  prop1: 'foo',
  prop2: 'bar',
  prop3: 'baz'
}

const filterKeys = (obj, keys = []) => {
  // NOTE: Clone object to avoid mutating original!
  obj = JSON.parse(JSON.stringify(obj))

  keys.forEach(key => delete obj[key])

  return obj
}

const result1 = filterKeys(obj, ['prop1', 'prop2'])
const result2 = filterKeys(obj, ['prop2'])

console.log(result1)
console.log(result2)

Method 2

There is no much you can do to simplify it, you can use an array

["a","b","c"].forEach(k => delete vm.model[k])

Method 3

Check this out:

> const {a,b, ...newArray} = {a:1,b:2,c:3,d:4}
> newArray
{ c: 3, d: 4 }

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply