LazioTibijczyk
LazioTibijczyk

Reputation: 1937

One liner to delete multiple object properties

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?

Upvotes: 2

Views: 7236

Answers (3)

nicholaswmin
nicholaswmin

Reputation: 22949

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)

Upvotes: 4

yukashima huksay
yukashima huksay

Reputation: 6238

Check this out:

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

Upvotes: 1

epascarello
epascarello

Reputation: 207521

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

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

Upvotes: 4

Related Questions