ES6 Destructuring: Transferring Values Between Objects
This question investigates the possibility of transferring values between existing objects using ES6 destructuring syntax. To better understand the scenario, let's assume we have two objects, foo and oof, where foo contains the properties x and y and oof is initially empty.
The query arises: can we utilize destructuring to assign foo's properties to oof akin to the hypothetical syntax oof{x,y} = foo?
While the suggested syntax is not valid, there is an alternative approach:
({x: oof.x, y: oof.y} = foo);
This expression effectively reads the x and y values from foo and writes them to the corresponding properties on oof. However, it's important to note that this approach can be somewhat repetitive and doesn't lend itself as well to cases where there are many properties to transfer.
Alternatively, a more concise solution is:
['x', 'y'].forEach(prop => oof[prop] = foo[prop]);
This method iterates through an array of property names, assigning the corresponding values from foo to oof for each property.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3