How to rename object keys in JavaScript? 4 Different Ways

Find out the different methods and techniques for JavaScript rename object keys.

And discover which one is best for your needs.

In this article, we will help you how to master the art of renaming object keys in JavaScript.

What is object keys in JavaScript?

Objects are collections of key-value pairs in JavaScript. The keys of an object are the names of its properties, and they are used to access the values stored in the object.

The keys can be strings or symbols, and they are unique within the object.

We can use various methods to work with the keys of an object, such as Object.keys(), which returns an array of the object’s own enumerable string-keyed property names.

How to rename an object key in JavaScript?

There’s no built-in function to rename object keys in JavaScript. However, there are different ways how we can rename object keys in JavaScript.

To rename object keys in JavaScript here are the different approaches you may use:

Solution 1: Using simple assignment

If you want to rename an object key in JavaScript, you can achieve it by assigning the value of the existing key to a new property with the desired key, and subsequently removing the original key property.

Here’s the syntax:

obj['New key'] = obj['old key'];

To rename an object key in a simple way, you can follow these steps:

  1. Assign the value of the old key to the new key using square bracket notation.
  2. Remove the old key using the delete operator.

This method is easy to use and can be applied to multiple keys and their corresponding values within an object.

For example:

let sample = [{
    "X": "Sourcecode"
}];
 
console.log(sample);
 
// This is the function wherein you can rename the old data
function rename() {
    sample = sample.map(function (obj) {
 
        // Give new data, you have to put the new and old data
        obj["It"] = obj["X"];
 
        //you have to delete the old data
        delete obj["X"];
 
        return obj;
    });
    console.log(sample);
}
 
rename();

Output:

[ { X: 'Sourcecode' } ] OLD
[ { It: 'Sourcecode' } ] NEW

You can also use this kind of approach:

let obj = {oldKey: 'value'};
console.log('Original object:', obj);

let oldKey = 'oldKey';
let newKey = 'newKey';

obj[newKey] = obj[oldKey];
delete obj[oldKey];

console.log('Renamed object:', obj);

Solution 2: Use object.defineProperty() method

To rename an object key in JavaScript, you can utilize the Object.defineProperty() method.

This approach involves defining a fresh property on the object, specifying the desired name, and assigning it the same value as the existing property.

Afterward, the old property is deleted. By adopting this method, the renamed property retains the identical behavior as the original one.

Here’s the syntax:

Object.defineProperty(obj, key, description) 

let data = [{
    "X": "Sourcecode"
}];
console.log(data);
 
// here's the Function to rename old data or key
function renameKey(obj, old_key, new_key) {
 
    if (old_key !== new_key) {
 
        // Update old data or key
        Object.defineProperty(obj, new_key,
 
            // get the description from object
            Object.getOwnPropertyDescriptor(obj, old_key));
 
        // this code will delete the old key
        delete obj[old_key];
    }
}
function rename() {
    data.forEach(obj => renameKey(obj, 'X', 'It'));
    console.log(data);
}
 
rename();

Output:

[ { X: 'Sourcecode' } ] OLD
[ { It: 'Sourcecode' } ] NEW

Solution 3: Use map() method

In order to change the names of multiple keys within an object, you can utilize the map() function to loop through the keys of the object.

For example:

function renameKeys(obj, newKeys) {
  const entries = Object.keys(obj).map(key => {
    const newKey = newKeys[key] || key;

    return {[newKey]: obj[key]};
  });

  return Object.assign({}, ...entries);
}

const obj = {oldKey1: 'X', oldKey2: 'Y', oldKey3: 'Z'};

const newKeys = {oldKey1: 'NEW1', oldKey2: 'NEW2', oldKey3: 'NEW3'};

console.log(renameKeys(obj, newKeys));

Output:

{ NEW1: 'X', NEW2: 'Y', NEW3: 'Z' }

Solution 4: Use Object.assign() method

This solution uses the Object.assign() method to rename a key in an object.

It creates a new object with the desired key name by copying all properties from one or more source objects to a target object.

Then, it deletes the old key from the new object. In short, this method helps create a new object with the renamed key.

For example:

let obj = {oldKey: 'X'};
console.log('Original object:', obj);

let oldKey = 'oldKey';
let newKey = 'Itsourcecode';

let newObj = {};
delete Object.assign(newObj, obj, {[newKey]: obj[oldKey]})[oldKey];

console.log('Renamed object:', newObj);

Output:

Original object: { oldKey: 'X' }
Renamed object: { Itsourcecode: 'X' }

Conclusion

In conclusion, this article explores different methods on how to rename object keys in JavaScript

Although there is no built-in function for this purpose, several approaches were presented.

By using the solutions given above, such as simple assignment, Object.defineProperty(), map(), and Object.assign().

You have a range of options to rename object keys according to your preference.

Whether renaming multiple keys, maintaining original behavior or handling a single key. These methods provide practical solutions for manipulating object keys in JavaScript.

We are hoping that this article provides you with enough information that helps you understand the JavaScript rename object keys.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment