One liner to delete multiple object properties

前端 未结 3 1396
被撕碎了的回忆
被撕碎了的回忆 2021-01-21 22:29

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

相关标签:
3条回答
  • 2021-01-21 22:39

    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.prop1, obj.prop2, obj.prop3)
        

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

    Just put the above loop into a function which you can reuse, i.e deleteKeys(obj, keys).

    0 讨论(0)
  • 2021-01-21 22:42

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

    ["a","b","c"].forEach(k => delete vm.model[k])
    
    0 讨论(0)
  • 2021-01-21 22:53

    Check this out:

    > const {a,b, ...newArray} = {a:1,b:2,c:3,d:4}
    > newArray
    { c: 3, d: 4 }
    
    0 讨论(0)
提交回复
热议问题