Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
LazioTibijczyk Avatar asked Nov 19 '25 10:11

LazioTibijczyk


2 Answers

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)
like image 116
nicholaswmin Avatar answered Nov 22 '25 00:11

nicholaswmin


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

["a","b","c"].forEach(k => delete vm.model[k])
like image 29
epascarello Avatar answered Nov 22 '25 00:11

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!