How to destructure an object based on a dynamic defined variable

问题: 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. const {countri...

问题:

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.

const {countries, remainder} = someObj // {countries:...,languages:..., ...keys};

This will end me up with the remainder being the new Object without the countries key.

Therefore I figured out that I could use reduce on an array to go through and remove all the values from the object, returning a new object in the end, using the default parameter, being the original object.

However, I am not sure how to go about it, because the names of keys are defined in the array.

arrayToRemove.reduce((total, value) => {
  const { extractValue: [value], ...remainder } = total
  return remainder;
}, { ...originalObj });

arrayToRemove.reduce((total, value) => {
  const { [extractValue], ...remainder } = total
  return remainder;
}, { ...originalObj });

I am expecting to end up with a new Object without the keys that are contained in the array called arrayToRemove.

I need to do this while maintaining immutability, so I cannot just loop through the original object and remove them from it, so I thought the above would be a bright way to go about it.

Any help is appreciated.


回答1:

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


回答2:

arrayToRemove.reduce((obj, key) => {
  const { [key]: value, ...remainder } = obj
  return remainder
}, originalObj)
  • 发表于 2019-01-08 02:56
  • 阅读 ( 197 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除