Introduction
In this lab, we will explore how to rename object keys in JavaScript. The lab will cover how to use Object.keys() and Array.prototype.reduce() in combination with the spread operator to get an object's keys and rename them according to a provided mapping. By the end of the lab, you will have a solid understanding of how to effectively rename object keys in your JavaScript code.
How to Rename Object Keys in JavaScript
To rename multiple object keys with the values provided, you can use the renameKeys function. Here are the steps you need to follow:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Object.keys()in combination withArray.prototype.reduce()and the spread operator (...) to get the object's keys and rename them according tokeysMap. - Pass the
keysMapand object (obj) as arguments to therenameKeysfunction. - The
renameKeysfunction returns a new object with the renamed keys.
Here's an example of how to use the renameKeys function:
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] }
}),
{}
);
const obj = { name: "Bobo", job: "Front-End Master", shoeSize: 100 };
renameKeys({ name: "firstName", job: "passion" }, obj);
// { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
Summary
Congratulations! You have completed the Rename Object Keys lab. You can practice more labs in LabEx to improve your skills.