One liner to delete multiple object properties

前端 未结 3 1400
被撕碎了的回忆
被撕碎了的回忆 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).

提交回复
热议问题