Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring of es6 but passing dynamic variable

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.

like image 333
Alex Yong Avatar asked Mar 08 '17 07:03

Alex Yong


1 Answers

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);
like image 171
Nina Scholz Avatar answered Sep 20 '22 12:09

Nina Scholz