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.
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)
}
2
Answers
you can transform roleListWithPermissions array to an object.
One approach is below, with explanatory comments in the code:
Reference:
Array.prototype.map()
.JSON.stringify()
.