Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to rename object properties in ES6

I'm still learning js and I need an advice. I get json object from backend, but keys have underscores. What is best practice to rename keys to, for example folder_name to Folder name? The list of properties is known and finished so I can keep new names in constants. At frontend I already use it like this:

const showPropertiesList = properties => Object.keys(properties).map(property => (
  <PropertyKey key={property}}>
    `${property}: ${properties[property]}`
  </PropertyKey>
));

It's better to use rename function in this map or create separate function before to get all renamed keys with values?

json file:

properties {
  folder_name: 'test',
  user_email: '[email protected]',
  user_agreed: 1,
  site: 'example.com',
}
like image 943
lukasz-p Avatar asked Mar 05 '18 01:03

lukasz-p


2 Answers

You can create some kind of a mapping object and then use the following combination of Object.keys and reduce functions:

const properties = {
  folder_name: "test",
  user_email: "[email protected]",
  user_agreed: 1,
  site: "example.com"
};

const mapping = {
  folder_name: "Folder name",
  user_email: "User email",
  user_agreed: "User agreed",
  site: "Site"
};

const mapped = Object.keys(properties).reduce((acc, key) => {
  acc[mapping[key]] = properties[key];
  return acc;
}, {});

console.log(mapped);
like image 69
Kirill Simonov Avatar answered Sep 30 '22 18:09

Kirill Simonov


try this:

const { folder_name: folderName, user_email: email, ...others } = originObject;
const renamedPropsObject = { folderName, email, ...others }
like image 43
Vladimir Popov Avatar answered Sep 30 '22 18:09

Vladimir Popov