Home >Web Front-end >JS Tutorial >Can You Destructure Onto an Existing Object in JavaScript ES6?
Can You Destructure Onto an Existing Object in JavaScript ES6?
Destructuring is a handy feature introduced in ES6 that allows for convenient extraction of data from objects and arrays. However, a common question arises: is it possible to destructure onto an existing object?
Consider the following scenario: you have two objects, foo and oof. You want to transfer the x and y values from foo to oof. While destructuring seems to be the ideal tool for this task, you may be curious if there's a way to achieve this directly with the ES6 destructuring syntax.
Attempting a Direct Transfer:
Intuitively, you might think of using a syntax like oof{x,y} = foo, but unfortunately, this doesn't work. Instead, JavaScript expects a new variable to be declared on the left-hand side of the assignment operator.
A Circumventing Solution:
To bypass this limitation, you can resort to a slightly unconventional but effective solution:
({x: oof.x, y: oof.y} = foo);
This line reads the x and y values from foo and assigns them to their respective locations in oof. While this approach may not be the most elegant, it accomplishes the desired goal.
Alternative Options:
For a more traditional approach, consider the following alternatives:
oof.x = foo.x; oof.y = foo.y;
['x', 'y'].forEach(prop => oof[prop] = foo[prop]);
These methods are perhaps more straightforward and maintain readability.
In Summary:
Destructuring onto an existing object is not directly supported in ES6 destructuring syntax. However, you can employ the given technique to achieve the desired outcome, or opt for traditional assignment approaches if clarity is a priority. Whether it's ({x: oof.x, y: oof.y} = foo);, oof.x = foo.x; oof.y = foo.y;, or a different method, the choice depends on your preferences and context.
The above is the detailed content of Can You Destructure Onto an Existing Object in JavaScript ES6?. For more information, please follow other related articles on the PHP Chinese website!