Home  >  Article  >  Web Front-end  >  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
Susan SarandonOriginal
2024-10-18 19:13:29522browse

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>

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>

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>

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!

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