Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript combine object

I’m trying to transform the object received from the to a format used in backend.
I receive this object

{
    'User.permissions.user.view.dashboard': true,
    'Admin.permissions.user.view.dashboard': true,
    'Admin.permissions.admin.view.dashboard': true,
}

The first part of the key (User, Admin) is the role name, the rest is the role. I need to combine this object into an object that has role names as keys for arrays containing the permission strings. The final result should look like this

{
    'User': [
        'permissions.user.view.dashboard'
    ],
    'Admin': [
        'permissions.user.view.dashboard',
        'permissions.user.admin.dashboard;
    ]
}

So far I managed to get this result, but I’m not sure how to combine the results

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const data = JSON.parse(req.body)
const permissions = Object.keys(data).map((key) => {
    const permParts = key.split('.')
    
    return {[permParts[0]]: permParts.slice(1).join('.')}
})
console.log(permissions);
[
  { User: 'permissions.user.view.dashboard' },
  { Admin: 'permissions.admin.view.dashboard' },
  { Admin: 'permissions.user.view.dashboard' }
]

>Solution :

const roleData = {
    'User.permissions.user.view.dashboard': true,
    'Admin.permissions.user.view.dashboard': true,
    'Admin.permissions.admin.view.dashboard': true,
};

const mappedData = Object.keys(roleData).reduce((acc, entry) => {
  const dotIndex = entry.indexOf('.');
  const parts = [entry.slice(0,dotIndex), entry.slice(dotIndex+1)];
  
  acc[parts[0]] ??= [];
  acc[parts[0]].push(parts[1]);
  return acc;
}, {});

console.log(mappedData);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading