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