DEV Community

Discussion on: Switch statements in javascript – How to refactor?

Collapse
 
vbarzana profile image
Victor A. Barzana

For example 2, having separate Objects to store the data related to pages is a bit misleading and accessing them by the lowercased output of another property could be buggy and not work as expected, what about storing all data in the same place?

const pageName = document.querySelector('#my-div').dataset.pageName;
const dataPageMapper = {
  homepage: {
        title: 'Home',
        layout: 'index'
  },
 productpage: {
        title: 'Product',
        layout: 'pdp'
  },
  blogpage: {
        title: 'Blog',
        layout: 'blog'
  }
};
const currentPage = dataPageMapper[pageName];
// and be careful with accessing properties of an object that doesn't match your pages config
console.log(currentPage.title + '_' + currentPage.layout);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ajayv1 profile image
Ajay Kumar Verma

Actually, I have taken the more general case when the clubbing is not possible i.e it could be the first object and 2nd object are seperate and coming from different files or place.

for this case though, we could have club the data.

Thanks for the suggestion!