Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

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);

Example:

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" };
Looking for help? At JetRockets, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.