首页 > 解决方案 > 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?

标签: javascriptangularjs

解决方案


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)


推荐阅读