Search code examples
javascriptreactjsecmascript-6

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',
}

Solution

  • 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],
      acc
    ), {});
    
    
    console.log(mapped);

    Or using creating a new object at each iteration:

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