Home > Blockchain >  Javascript combine object
Javascript combine object

Time:12-07

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

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

CodePudding user response:

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

CodePudding user response:

You can use reduce function:

const result = permissions.reduce((acc, cur) => {
  const key = Object.keys(cur)[0]
  if (acc[key]) {
    acc[key] = [...acc[key], cur[key]]
  } else {
    acc[key] = [cur[key]]
  }
  return acc
}, {})
  • Related