Home  >  Article  >  Web Front-end  >  How to Destructure Properties into an Existing Object in JavaScript ES6?

How to Destructure Properties into an Existing Object in JavaScript ES6?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 20:50:30163browse

How to Destructure Properties into an Existing Object in JavaScript ES6?

Destructuring into Existing Objects in JavaScript ES6

In ES6, destructuring allows you to assign properties from one object to another. However, you may encounter a scenario where you want to transfer properties into an existing object rather than creating a new one.

Question:

How can you destructure properties onto an existing object in JavaScript ES6, such as transferring values from one object (e.g., foo) to another (e.g., oof)?

Answer:

While not explicitly supported by ES6 destructuring syntax, there is an alternative approach that achieves the desired result:

<code class="javascript">({x: oof.x, y: oof.y} = foo);</code>

By wrapping the destructuring assignment in parentheses and using the existing properties of oof as keys, you can read the values from foo and write them to the corresponding keys on oof. However, this approach is not as concise or elegant as some alternatives:

  • Direct Assignment:
<code class="javascript">oof.x = foo.x;
oof.y = foo.y;</code>
  • Array-Based Loop:
<code class="javascript">['x', 'y'].forEach(prop => oof[prop] = foo[prop]);</code>

Ultimately, the choice of approach depends on personal preference and the specific use case.

The above is the detailed content of How to Destructure Properties into an Existing Object 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