Home > Article > Web Front-end > Can You Transfer Object Values with ES6 Destructuring?
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:
<code class="javascript">({x: oof.x, y: oof.y} = foo);</code>
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:
<code class="javascript">['x', 'y'].forEach(prop => oof[prop] = foo[prop]);</code>
This method iterates through an array of property names, assigning the corresponding values from foo to oof for each property.
The above is the detailed content of Can You Transfer Object Values with ES6 Destructuring?. For more information, please follow other related articles on the PHP Chinese website!