2

my linter is giving me trouble about destructuring.

enter image description here


When I'm trying to destructure, it makes me an error, like in the following snippet :

const data = {
  status: 'example',
};

let status = 'foo';

{
  status,
} = data;

console.log(status);

Is there any ways to use destructuration when the variable already exists?


Using let again :

const data = {
  status: 'example',
};

let status = 'foo';

let {
  status,
} = data;

console.log(status);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • Missing statement `let` `->` `let { status } = data;` This will raise an error because the variable already exists, so do this `->` `let { status: myOwnStatus } = data;` – Ele Jul 03 '19 at 08:42
  • Possible duplicate of [Is it possible to destructure onto an existing object? (Javascript ES6)](https://stackoverflow.com/questions/29620686/is-it-possible-to-destructure-onto-an-existing-object-javascript-es6) – Roberto Zvjerković Jul 03 '19 at 08:44
  • Well it's literally the same. Just add parens. – Roberto Zvjerković Jul 03 '19 at 08:55
  • I've badly expressed myself. I meant that there was no answer fitting what I wanted to do. @adiga answer is perfect – Orelsanpls Jul 03 '19 at 08:57
  • But there is a fitting answer in the question I have linked. It's the first answer, which is by the way also the accepted answer. It says "just add the parens around the destructuring". I will quote the second line of the accepted answer: `({x: oof.x, y: oof.y} = foo);` – Roberto Zvjerković Jul 03 '19 at 17:34
  • @ritaj Right I didn't saw it properly ^^' my bad thx for the input – Orelsanpls Jul 03 '19 at 18:29

1 Answers1

12

Add parenthesis around destructuring

From the documentation: Assignment without declaration

The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

const data = {
  status: 'example',
};

let status = 'foo';

({ status } = data);

console.log(status);
Community
  • 1
  • 1
adiga
  • 34,372
  • 9
  • 61
  • 83