"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Rename Key Names in Arrays of Objects in JavaScript?

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

Published on 2024-11-09
Browse:394

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'
}]
Release Statement This article is reprinted at: 1729249819 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3