3

I have an object. I know I can destructure to retrieve the value of any entry, and use spread operator to retrieve the rest of them

const [a, ...rest] = [1, 2, 3];
console.log(a); // 1
console.log(rest); // [ 2, 3 ]

I would like to know if there is any sintaxis to retrieve both a value of any entry, and the object itself redeclared to a new var, something like the following —although I know is wrong—:

const [a], myArrayInANewVar = [1, 2, 3];
console.log(a); // 1
console.log(myArrayInANewVar); // [ 1, 2, 3 ]

Thanks in advance!

Emille C.
  • 442
  • 5
  • 18

2 Answers2

1

Why not take two assignments?

const myObject = {
  a: 1,
  b: 2,
};

const
    { a } = myObject,
    { ...copy } = myObject;

console.log(a);
console.log(copy);

A chained assignemnt does not work because the nested variables are created outside of the actual scope.

function ownScope() {
    const
        myObject = { a: 1, b: 2, },
        { a } = { ...copy } = myObject;

    console.log(a);
    console.log(copy);
}

ownScope();
console.log(copy); // global
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
  • Sorry, updated the example: lets say that we don't have the array/object in a variable, but we want to destructure the array/object directly. Also updated to use an array, although I expect will be similar syntax —if it exist— – Emille C. Dec 18 '20 at 09:48
0
const [a] = (myArrayInANewVar = [1, 2, 3]);
console.log(a); // 1
console.log(myArrayInANewVar); // [ 1, 2, 3 ]
Emille C.
  • 442
  • 5
  • 18
  • 1
    right, i was thinking of myself of this structure with a chained assingment, the drawback of this construction is to get a global variable outside of the scope for the inner variable. to proof this, you could move all into a function and call `myArrayInANewVar` outside. – Nina Scholz Dec 18 '20 at 09:52