-3

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!

Laurent Dhont
  • 1,012
  • 1
  • 9
  • 22
  • 1
    It's not very clear what you're asking nor is it clear why your two-line simple solution is not sufficient. – Phil Nov 13 '19 at 00:30

3 Answers3

0

Try to use async/await function and it will work.

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

Rise
  • 1,493
  • 9
  • 17
  • 1
    What is this, where did you find it, how does OP use it, and how does it solve the problem? Answers without explanations are not very valuable and this one should be a comment instead. – Andreas Nov 13 '19 at 01:26
  • I think one line code is just enough to show it in one line as asked in question. Basically, that's a general syntax and I don't think it should have explanation for this 1 line. – Rise Nov 13 '19 at 01:33
  • Thanks a lot, please see my question again. I asked it wrong. First time here... – Laurent Dhont Nov 14 '19 at 21:32
  • Yes, this I already now, this is in my question. I want to know how I can do this: `testObject2.property1 = await testObject1.first;` – Laurent Dhont Nov 19 '19 at 20:58
  • 1
    Try this. testObject2.property1 = (await getTestObject()).first; – Rise Nov 20 '19 at 00:22
0

No need to destructure...

testObject2.property1 = testObject1.first;
0

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.

Beyers
  • 8,968
  • 43
  • 56