How to destructure an object based on a dynamic defined variable

后端 未结 2 502
独厮守ぢ
独厮守ぢ 2021-01-06 16:52

I am working with an immutable object that I need to add subtract an array of values from.

I know it\'s possible using ES6 destructing with the following.

         


        
相关标签:
2条回答
  • 2021-01-06 17:32
    arrayToRemove.reduce((obj, key) => {
      const { [key]: value, ...remainder } = obj
      return remainder
    }, originalObj)
    
    0 讨论(0)
  • 2021-01-06 17:41

    You could use a computed property names with a dummy as target property.

    Read more here: object property assignment pattern [YDKJS: ES6 & Beyond]

    var originalObj = { foo: 1, bar: 2, baz: 3, },
        arrayToRemove = ['foo', 'bar'],
        result = arrayToRemove.reduce((total, key) => {
            const { [key]: dummy, ...remainder } = total;
            return remainder;
        }, originalObj);
    
    
    console.log(result);

    0 讨论(0)
提交回复
热议问题