Search code examples
javascriptdestructuring

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:

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.

The normal way I would do this is:

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

TestObject1 is returned from an async 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.

But I want to do this in 1 line with destructuring and I can't find a way to do this.

Thanks!


Solution

  • 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. 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.