简体   繁体   English

JS解构成其他变量

[英]JS destructuring into other variable

I am not sure this is even possible.我不确定这是否可能。 I don't know how to do this.我不知道该怎么做。

So I have these object:所以我有这些 object:

const testObject1 = {first: 25, second: 2}; 
let testObject2 = {property1: 0, property2: 29};

and I want to put the "first" property of testObject1 in "property1" of testObject2.我想把testObject1的“第一个”属性放在testObject2的“property1”中。

The normal way I would do this is:我这样做的正常方法是:

const {first} = testObject1; 
testObject2.property1 = first;

TestObject1 is returned from an async function. TestObject1 从异步 function 返回。 So the syntax I am looking for would look something like this: testObject2.property1 = await asyncFunction().first but I know this doesn't work.所以我正在寻找的语法看起来像这样: testObject2.property1 = await asyncFunction().first但我知道这不起作用。

But I want to do this in 1 line with destructuring and I can't find a way to do this.但是我想在 1 行中使用解构来做到这一点,但我找不到这样做的方法。

Thanks!谢谢!

Try to use async/await function and it will work.尝试使用 async/await function 它将起作用。

const testObject1 = {first: 25, second: 2};

let testObject2 = {property1: 0, property2: 29};

const getTestObject = function() {
    return new Promise((resolve) => {
        setTimeout(function() {
            resolve(testObject1);
        }, 3000);
    })
}

const test = async () => {
    const testObject1 = await getTestObject();
    if (testObject1.first) {
        const {first} = testObject1; 
        testObject2.property1 = first;
    }

}

test();

console.log(testObject2); // {property1: 25, property2: 29}

Official guide: async function官方指南: async function

No need to destructure...不需要解构...

testObject2.property1 = testObject1.first;

Just enclose the await call inside round brackets () which will ensure that whatever is inside the brackets are executed first, in your example the object that resolves from asyncFunction() will be available after the brackets.只需将 await 调用括在圆括号()内,这将确保首先执行括号内的任何内容,在您的示例中,从asyncFunction()解析的 object 将在括号后可用。 As an example:举个例子:

testObject2.property1 = (await asyncFunction()).first;

Note you wont be able to check for null or undefined values, so this method is not always a good idea.请注意,您将无法检查 null 或未定义的值,因此这种方法并不总是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM