How to destructure an object to an already defined variable?

JavascriptEcmascript 6

Javascript 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);

Babel REPL Example

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGajusView Question on Stackoverflow
Solution 1 - JavascriptCodingIntrigueView Answer on Stackoverflow