Skip to content Skip to sidebar Skip to footer

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 prope

Solution 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)

Solution 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])

Solution 3:

Check this out:

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

Post a Comment for "One Liner To Delete Multiple Object Properties"