We are given an object with multiple key-value pairs and a set of user-defined key replacements. We need to rename one or more keys in the object with the new names provided by the user, while keeping their corresponding values unchanged.
- Renames one or more object keys with new names.
- Preserves the values associated with the renamed keys.
- Supports direct replacement as well as dynamic key mapping.
Approach 1: Direct Key Replacement
The idea is to directly assign the value of the existing key to the new key and then delete the old key. This renames the key while keeping its value unchanged.
Example 1: Renames the name key to FirstName while preserving its value.
let object = {
name: "Hello",
age: 20,
gender: "Male"
};
// Function to rename 'name' key to 'FirstName'
let renameObjectKey = (object) => {
// Assign value of 'name' to 'FirstName'
object.FirstName = object.name;
// Remove old 'name' key
delete object.name;
};
renameObjectKey(object);
console.log(object);
Output:
{ age: 20, gender: 'Male', FirstName: 'Hello' }Example 2: Renames both the name and age keys to FirstName and currentAge.
let object = {
name: "Hello",
age: 20,
gender: "Male"
};
// Function to rename multiple keys
let renameObjectKeys = (object) => {
object.FirstName = object.name;
object.currentAge = object.age;
delete object.name;
delete object.age;
};
renameObjectKeys(object);
console.log(object);
Output:
{ gender: 'Male', FirstName: 'Hello', currentAge: 20 }Note: The position of the renamed keys may change because they are added as new properties, but their values remain unchanged.
Approach 2: Using Object.keys() with reduce()
The idea is to use a keysMap object containing the old-to-new key mappings. Object.keys() iterates over the object keys, while reduce() creates a new object with the updated key names.
Example: Renames multiple keys using a user-defined mapping while preserving their values.
let object = {
name: "Hello",
age: 20,
gender: "Male"
};
// Function to rename keys using keysMap
let renameObjectKeys = (keysMap, obj) => {
return Object.keys(obj).reduce((acc, key) => {
// Replace key if mapping exists
const newKey = keysMap[key] || key;
acc[newKey] = obj[key];
return acc;
}, {});
};
// Mapping of old keys to new keys
let keysMap = {
name: "FirstName",
age: "currentAge"
};
// Driver Code
let result = renameObjectKeys(keysMap, object);
console.log(result);
Output:
{ FirstName: 'Hello', currentAge: 20, gender: 'Male' }Note: This approach creates a new object and replaces only the keys specified in keysMap, while preserving their corresponding values.