2

I am trying to assign and destructure at the same time

a = {x: 1, y: 5}
let b, {x} = a

result:

b = undefined
x = 1

I want:

b = {x: 1, y: 5}
x = 1

Is there any way to achieve that ? When I try to assign with const

const c, {y} = a
      ^
Uncaught SyntaxError: Missing initializer in const declaration
A1I
  • 39
  • 7
  • 1
    `const b = a, {x} = a`? Although that doesn't *copy* the object. – VLAZ Mar 24 '21 at 09:32
  • let a = {x: 1, y: 5} let b = {x} = a; – Ravi Ashara Mar 24 '21 at 09:33
  • 1
    @RaviAshara that creates an implicit global `x` (which throws an error in strict mode) – adiga Mar 24 '21 at 09:38
  • If you want a shallow copy. `const b = {...a}, {x} = a` – Keith Mar 24 '21 at 09:44
  • 1
    Assigning multiple variables in a single expression is confusing enough. Adding destructuring on top is even worse. You might like it, most of your colleagues won't. If I see something like that, I will immediately refactor it. Please, have mercy to others. – zhulien Mar 24 '21 at 09:45
  • `const { b = a, x } = a;`Assign the default value `a` to `b`. – DecPK Mar 24 '21 at 09:50

1 Answers1

0

You could wrap a in an object and destructure a with a renaming to b and take the nested x directly.

const
    a = { x: 1, y: 5 },
    { a: b, a: { x } } = { a };

console.log(b);
console.log(x);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392