Home > Software design >  Convert Dynamic List into JSON object
Convert Dynamic List into JSON object

Time:12-08

I am allowing my users to create different roles for themselves within my svelteKit application. I have a text input with a button that adds that value to an array and shows in the div below.

enter image description here

I need to convert the array into a tiered JSON object so I can add it to my Postgres database role_permissions column as JSONB. I have tried JSON.stringify() and JSON.parse() but I cannot get it to work.

Ideally formatted like this:

{
  "role_name"{
            "permission": true,
            "permission": true,
             ...
             }
  "role_name_2"{
            "permission": true,
            "permission": false,
             ...
             }
}

While my users can create roles with custom names the permissions available are all the same e.g.:

can_add_members: false,
can_delete_members: false,
can_edit_members: false,

can_create_roles: false,
can_delete_roles: false,
can_edit_roles: false,
can_assign_roles: false,

can_create_projects: false,
can_delete_projects: false,
can_edit_projects: false,
can_publish_projects: false,
can_view_projects: false,

can_assign_members_to_projects: false,

I can't figure out how to convert the object into a tiered JSON format. I know I need some sort of key outside of each object but I do not know how to do that.

This is how they appear in console.log()

{name: "Partner", can_add_members: false, can_delete_members: false, can_edit_members: false, can_create_roles: false, …}
{name: "Associate Partner", can_add_members: false, can_delete_members: false, can_edit_members: false, can_create_roles: false, …}

The actual code:

    let newItem = '';
    
    // An array of the roles names that will also be saved to the database as is.
    let roleList = [];

    // The array that needs to be converted to JSON
    let roleListWithPermissions = [],
    
    function addToList() {
        roleList = [...roleList, {text: newItem,}];

        roleListWithPermissions = [...roleListWithPermissions, {
            "name": newItem,
            "can_add_members": false,
            "can_delete_members": false,
            "can_edit_members": false,

            "can_create_roles": false,
            "can_delete_roles": false,
            "can_edit_roles": false,
            "can_assign_roles": false,
            
            "can_create_projects": false,
            "can_delete_projects": false,
            "can_edit_projects": false,
            "can_publish_projects": false,
            "can_view_projects": false,

            "can_assign_members_to_projects": false
        }];
           
            newItem = '';
            console.log("ROLE LIST",roleList)
            console.log("PERMISSIONS LIST",roleListWithPermissions)
          
    } 

CodePudding user response:

One approach is below, with explanatory comments in the code:

// the original Object as described/shown in the question:
let source = [{
      name: "Partner",
      can_add_members: false,
      can_delete_members: false,
      can_edit_members: false,
      can_create_roles: false,
    },
    {
      name: "Associate Partner",
      can_add_members: false,
      can_delete_members: false,
      can_edit_members: false,
      can_create_roles: false,
    }
  ],
  // here we use Array.prototype.map() to iterate over the Array of Objects:
  rolePermissions = source.map(
    // using destructuring assignment to retrieve the 'name'
    // property from the Array-element (the Object),
    // and assigning all remaining property-value pairs
    // to the 'rest' variable:
    ({
      name,
      ...rest
    }) => {
      // here we return a new Object, with the computed value of the
      // 'name' variable to set the property equal to the value of the
      // variable rather than the String of 'name':
      return {
        // and the property-value equal to the Object containing the 
        // rest of the key-value pairs:
        [name]: rest
      };
    }),
  // converting the Array of Objects into a JSON string:
  jsonRolePermissions = JSON.stringify(rolePermissions);
// logging that JSON string to the console:
console.log(jsonRolePermissions);

Reference:

CodePudding user response:

you can transform roleListWithPermissions array to an object.

const finalResult =
  roleListWithPermissions.reduce((result, current) => {
    result[current.name]= {...current};
    delete result[current.name].name;
    return result;
   }, {})
  • Related