Home >Web Front-end >JS Tutorial >Can You Destructure Values Onto Existing Objects in JavaScript ES6?

Can You Destructure Values Onto Existing Objects in JavaScript ES6?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 07:28:30918browse

 Can You Destructure Values Onto Existing Objects in JavaScript ES6?

Destructuring onto Existing Objects in JavaScript ES6

In JavaScript ES6, destructuring allows for the concise extraction of values from objects and arrays into variables. However, many developers seek to transfer values onto preexisting objects using destructuring syntax.

Consider the following scenario:

<br>var foo = {<br>  x: "bar",<br>  y: "baz"<br>};<br>var oof = {};<br>

We seek to transfer the x and y values from foo to oof via ES6 destructuring. While ES6 does not explicitly support this behavior, there is a workaround:

({x: oof.x, y: oof.y} = foo);

This code reads the x and y values from foo and writes them to their respective locations in oof. However, it's not the most elegant solution. Other alternatives include:

oof.x = foo.x;
oof.y = foo.y;

or:

['x', 'y'].forEach(prop => oof[prop] = foo[prop]);

While more verbose, these alternatives are generally considered more readable than the destructuring workaround.

The above is the detailed content of Can You Destructure Values Onto Existing Objects in JavaScript ES6?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn