Home >Web Front-end >JS Tutorial >How to Rename Key Names in Arrays of Objects in JavaScript?

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

DDD
DDDOriginal
2024-10-18 19:12:03935browse

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'}];

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
    }) 
  2. Spread Syntax:
    Use spread syntax to copy the remaining key-value pairs into a new object:

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

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

Example:

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

console.log(newArrayOfObj);

Output:

[{
  stroke: 'value1',
  key2: 'value2'
}, {
  stroke: 'value1',
  key2: 'value2'
}]

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!

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