Skip to content Skip to sidebar Skip to footer

Destructure Object Property AND Whole Object Itself

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

Solution 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

Solution 2:

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

Post a Comment for "Destructure Object Property AND Whole Object Itself"