I have an object of data that is loaded from a database. A user can select options on the page and for each of those options that don't exist in the initial object, I need to create them.
I wrote up some psuedo code for what I am attempting here, its causing a memory issue though and crashing.
The goal here is that I iterate over each task > Roles array and check to see if theres any missing objects that need to be created. The object that need to be created come from selectedRoles.
Desired Outcome:
In the first task, it should create 3 roles as its currently empty. In the second task, it would create roles 1 and 3 because a role with the id of 2 already exists.
var tasks = [{
"User": {
"FirstName": "Joe",
"LastName": "Dirt",
"selected": false,
"marked": false
},
"Tool": {
"id": 31,
"text": "Admin",
"ToolID": "31",
"ToolName": "Admin",
"ToolSuite": "Enterprise Product"
},
"Roles": []
}, {
"User": {
"FirstName": "Bart",
"LastName": "Simpson",
"selected": false,
"marked": false
},
"Tool": {
"id": 35,
"text": "Wordpress",
"ToolID": "35",
"ToolName": "Wordpress",
"ToolSuite": "Enterprise Product"
},
"Roles": [{
RoleName: 'Role 2',
Role: 2,
RoleID: 2
}]
}];
// New selected roles from list
var selectedRoles = [1, 2, 3];
////////////////////////////////////////////////////////////////////////
/*
Loop over the configured tasks and
if there is not an existing role
matching a role id from "SelectedRoles",
create a new role within that task.
*/
// Loop over the tasks
tasks.forEach((task) => {
// If we have roles, loop over them
if (task.Roles.length) {
for (let i = 0; i < task.Roles.length; i++) {
// If this roleID does not exist in our selectedRoles, create the task
if(selectedRoles.indexOf(task.Roles[i].RoleID) >= 0){
// Create this role and add it to our task
task.Roles.push(createRole('Role ' + task.Roles[i].RoleID, task.Roles[i].RoleID, task.Roles[i].RoleID));
}
}
}
});
console.log(tasks)
function createRole(RoleName, RoleID, Role){
return {
RoleName: RoleName,
RoleID: RoleID,
Role: Role
}
}
Any thoughts on a more clean (and working) way to handle this?