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:
Destructuring with Rest Syntax:
Extract the old key-value pair and rename the key as shown:
({ key1: stroke, ...rest })
Spread Syntax:
Use spread syntax to copy the remaining key-value pairs into a new object:
({ stroke, ...rest })
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!