Rename the key name in the javascript object

How to rename the key name in the javascript object? That’s easy!

Lets create function to do that:

const renameKey = (object, key, newKey) => {

  const clonedObj = clone(object);

  const targetKey = clonedObj[key];

  delete clonedObj[key];

  clonedObj[newKey] = targetKey;

  return clonedObj;


Here is clone function:

const clone = (obj) => Object.assign({}, obj);


let contact = { 

    id: 1, 

    name: "contact name"


contact = renameKey(contact, 'id', 'value');

contact = renameKey(contact, 'name', 'label');

console.log(contact); // { value: 1, label: "contact name" };

2868e927 153f 4f5c 96bf 8bf0187ba2a9 rectangle 400 x

Frontend Developer at JetRockets