Home > Web Front-end > JS Tutorial > body text

Can You Destructure Values Onto Existing Objects in JavaScript ES6?

Barbara Streisand
Release: 2024-10-28 07:28:30
Original
834 people have browsed it

 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);
Copy after login

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;
Copy after login

or:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!