Home > Web Front-end > JS Tutorial > How to Modify Key Names in an Array of Objects (Renaming Keys)?

How to Modify Key Names in an Array of Objects (Renaming Keys)?

Susan Sarandon
Release: 2024-10-18 19:13:29
Original
610 people have browsed it

How to Modify Key Names in an Array of Objects (Renaming Keys)?

Modifying Key Names in an Array of Objects

Consider an array of objects:

<code class="javascript">var arrayObj = [
  { key1: 'value1', key2: 'value2' },
  { key1: 'value1', key2: 'value2' }
];</code>
Copy after login

To change all occurrences of "key1" to "stroke", utilize a combination of destructuring, rest, and spread syntax along with the map() function.

<code class="javascript">const newArrayOfObj = arrayObj.map(({ key1: stroke, ...rest }) => ({
  stroke,
  ...rest
}));</code>
Copy after login

This approach simultaneously destructures the object, renames "key1" to "stroke", and spreads the remaining properties into the new object.

The resulting newArrayOfObj would resemble:

<code class="javascript">[{ stroke: 'value1', key2: 'value2' }, { stroke: 'value1', key2: 'value2' }]</code>
Copy after login

The above is the detailed content of How to Modify Key Names in an Array of Objects (Renaming Keys)?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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