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

How to Rename Key Names in Arrays of Objects in JavaScript?

DDD
Release: 2024-10-18 19:12:03
Original
842 people have browsed it

How to Rename Key Names in Arrays of Objects in JavaScript?

Renaming Key Names in Arrays of Objects

In Javascript, you may encounter the need to change the key names within an array of objects. For instance, converting key1 to stroke:

var arrayObj = [{key1:'value1', key2:'value2'},{key1:'value1', key2:'value2'}];
Copy after login

To change the key, employ the following steps:

  1. Destructuring with Rest Syntax:
    Extract the old key-value pair and rename the key as shown:

    ({
      key1: stroke,
      ...rest
    }) 
    Copy after login
  2. Spread Syntax:
    Use spread syntax to copy the remaining key-value pairs into a new object:

    ({
      stroke,
      ...rest
    })
    Copy after login
  3. Array Map:
    Apply these changes to each object in the array using map():

    arrayOfObj.map(({
      key1: stroke,
      ...rest
    }) => ({
      stroke,
      ...rest
    }))
    Copy after login

Example:

const arrayOfObj = [{
  key1: 'value1',
  key2: 'value2'
}, {
  key1: 'value1',
  key2: 'value2'
}];
const newArrayOfObj = arrayOfObj.map(({
  key1: stroke,
  ...rest
}) => ({
  stroke,
  ...rest
}));

console.log(newArrayOfObj);
Copy after login

Output:

[{
  stroke: 'value1',
  key2: 'value2'
}, {
  stroke: 'value1',
  key2: 'value2'
}]
Copy after login

The above is the detailed content of How to Rename Key Names in Arrays of Objects in JavaScript?. 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
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!