How to destructure an object to an already defined variable?
JavascriptEcmascript 6Javascript Problem Overview
The following produces a syntax error:
let source,
screenings,
size;
source = {
screenings: 'a',
size: 'b'
};
{
screenings,
size
} = source;
Expected result:
screenings should be equal to 'a'
size should be equal to 'b'
Javascript Solutions
Solution 1 - Javascript
You need to use assignment separate from declaration syntax:
({
screenings,
size
} = source);
From the linked docs:
> The ( .. ) around the assignment statement is required syntax when > using object literal destructuring assignment without a declaration
And obviously you need to use this as you can't redeclare a let
variable. If you were using var
, you could just redeclare var { screenings, size } = source;