Categories
JavaScript Answers

How to change the key name in an array of objects with JavaScript?

Spread the love

Sometimes, we want to change the key name in an array of objects with JavaScript.

In this article, we’ll look at how to change the key name in an array of objects with JavaScript.

How to change the key name in an array of objects with JavaScript?

To change the key name in an array of objects with JavaScript, we use the array map method.

For instance, we write

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

console.log(newArrayOfObj);

to call arrayOfObj.map with a function that destructures the object we’re iterating through.

Then we return a new object that has the stroke property and the rest object’s properties spread into the returned object.

rest is an object with properties other than key1.

We rename key1 to stroke when we’re destructuring.

Conclusion

To change the key name in an array of objects with JavaScript, we use the array map method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *