my linter is giving me trouble about destructuring.
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);
my linter is giving me trouble about destructuring.
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);
Share
Improve this question
edited Jul 3, 2019 at 8:44
Orelsanpls
asked Jul 3, 2019 at 8:40
OrelsanplsOrelsanpls
23.6k7 gold badges46 silver badges73 bronze badges
6
-
Missing statement
let
->
let { status } = data;
This will raise an error because the variable already exists, so do this->
let { status: myOwnStatus } = data;
– Ele Commented Jul 3, 2019 at 8:42 - Possible duplicate of Is it possible to destructure onto an existing object? (Javascript ES6) – Roberto Zvjerković Commented Jul 3, 2019 at 8:44
- Well it's literally the same. Just add parens. – Roberto Zvjerković Commented Jul 3, 2019 at 8:55
- I've badly expressed myself. I meant that there was no answer fitting what I wanted to do. @adiga answer is perfect – Orelsanpls Commented Jul 3, 2019 at 8: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ć Commented Jul 3, 2019 at 17:34
1 Answer
Reset to default 14Add 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 isvar {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);