How to rename object key in JavaScript?
Renaming an object’s key is quite simple and easy. We can achieve this in multiple ways. We can create a new property by using this method: Object.defineProperty
and delete the old property using delete
. Following is a custom function do rename an object’s key:
const renameObjectKey = (obj, new_key, old_key) => { if (old_key !== new_key) { Object.defineProperty(obj, new_key, Object.getOwnPropertyDescriptor(obj, old_key)); delete obj[old_key]; } }; const userObj = { name: 'Joe Smith', email: 'joe@example.com', }; renameObjectKey(userObj, 'fullname', 'name');
If we are looking for a one-liner and want to use Object.assign
method, we can easily do that using the following code:
const userObj = { name: 'Joe Smith', email: 'joe@example.com', }; delete Object.assign(userObj, {['fullname']: userObj['name'] })['name']; console.log(userObj);
In case we want to create a new object instead of modifying the original object, we can do that using the following code segment.
const userObj = { name: 'Joe Smith', email: 'joe@example.com', }; const userNewObj = {}; delete Object.assign(userNewObj, userObj, {['fullname']: userObj['name'] })['name']; console.log(userNewObj);