0

I have a message from my websocket:

var message = {
  spell: {
    symbol: 'my-spell'
  },
  target: {
    symbol: 'my-target'
  }
};

I'm trying to learn destructuring, so I wrote the following code:

let {
  spell: {
    spell_symbol: symbol
  },
  target: {
    target_symbol: symbol = null
  }
} = message;
console.log('spell symbol: ' + spell_symbol);
console.log('target symbol: ' + target_symbol);

This gives me an error:

SyntaxError: Identifier 'symbol' has already been declared

Have I written the syntax wrong, or can you not reuse keys like symbol in your nested object? How would I extract target.symbol from message?

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
whiterook6
  • 3,270
  • 3
  • 34
  • 77

1 Answers1

2

You mixed up the order of property name and target expression, it should be

const {
  spell: {
    symbol: spell_symbol
  },
  target: {
    symbol: target_symbol = null
  }
} = message;
console.log('spell symbol: ' + spell_symbol);
console.log('target symbol: ' + target_symbol);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • @DavidBray See [here](https://stackoverflow.com/a/40698920/1048572) or [there](https://stackoverflow.com/a/43903662/1048572) for an explanation – Bergi Jan 06 '19 at 21:39