Search code examples
javascriptdestructuring

Destructuring but also returning the source object


One can do

import Foo, { bar } from 'foo-with-bar'

However, is something similar possible using destructuring, like

let { * as Foo, bar } = getFooBar()

?

Let's assume getFooBar() and the foo-with-bar module return

{ foo: 1, bar: a => console.log(a) }

and after the import/let, this is expected to print 1:

bar(Foo.foo)

Solution

  • No, if you're doing destructuring you already have split the object up in properties. However you can just use two assignments:

    let Foo = getFooBar();
    let { bar } = Foo;
    

    or:

    let Foo, { bar } = Foo = getFooBar(); // very questionable and unmaintainable
    let Foo = getFooBar(), { var } = Foo; // better
    

    There is also a object rest property proposal with an experimental transpiler plugin that lets you do

    let { bar, ...Foo } = getFooBar();
    

    but Foo will be a new object here and lack the bar property.