2

Sorry I know this is really a dumb question, but I couldn't find the answer after a couple of rounds googling. Code looks like below:

let x = 0
// After some calculation I know the obj should be:
const obj = {'x': 1 }
// Then how to destructuring assigment at this line
{ x } = obj // this is incorrect
// But if I use: x = obj.x, ESLint warns me: [eslint] Use object destructuring. (prefer-destructuring)

console.log(x);

So my question is how to use destructuring assignment after x has been defined.

LiuWenbin_NO.
  • 1,216
  • 1
  • 16
  • 25
  • I don't see a problem, `const obj = {'x': 1}; const { x } = obj;` works fine. Could you show more code? – dhilt Jul 13 '18 at 03:09
  • @SamHolmes Thank you! I get the answer from your link! – LiuWenbin_NO. Jul 13 '18 at 03:16
  • @dhilt I have defined `let x = 0` before destructuring assignment. Which is different to your sample code, yours is destructuring assign on x on the fly of definition. Thank you all the same! – LiuWenbin_NO. Jul 13 '18 at 03:17

1 Answers1

0

The initialization and destructing should happen in the same line. If you want to set an initial value, why not use default value assignment.

let { x = 0 } = obj

Sushanth --
  • 55,259
  • 9
  • 66
  • 105