16

Says my state is like this:

{
  item:{
      a:'a',
      b:'b'
  }
}

Then I'm able to pull a from item by doing:

const { a } = this.state.item

but can pull dynamically using {} of es6 ?

For example const { variable } = this.state.item, where variable can be a or b.

kissu
  • 40,416
  • 14
  • 65
  • 133
Alex Yong
  • 7,425
  • 8
  • 24
  • 41
  • 4
    You can't re-define a `const` to have a different value. What variable should hold the output? I looks like you will need [computed property destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Computed_object_property_names_and_destructuring) – 4castle Mar 08 '17 at 07:12

2 Answers2

26

As 4castle pointet out, you could use Computed object property names and destructuring with an additional key/value pair variables for destructuring.

var object = { item: { a: 'a0', b: 'b0' } },
    key = 'b',
    value;

({ [key]: value } = object.item);

console.log(value);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1
const handleChange = (e) => {
        const { name, value } = e.target;
        const { [name]: property, ...rest } = coupon;
        setNewValue({ [name]: value, ...rest });
    }
N I Rimon
  • 36
  • 4