Destructure object property AND whole object itself [duplicate]

久未见 提交于 2021-01-28 11:20:51

问题


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!


回答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



回答2:


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


来源:https://stackoverflow.com/questions/65354700/destructure-object-property-and-whole-object-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!