I want to create an object with nested arrays that will look something like this:
[{"name":"Joe","role":["Admin","Developer"]},{"name":"Sherry","role":["Analyst","QA-tester"]}]
I want to be able to do things like find the roles array for Sherry and add more values to that array. How can I go about this?
employees = [];
// [*query database for names and associated roles*]
employees.push({name: exampleVar1,role:exampleVar2});
Expected results: I want to store names that I can use to insert roles associated to the employee. Then later use this object as a reference.
You could use a function that will find the employee (or create it, if not found), add the role(s) and make sure a role will not be added, if already present:
function addRoles(employees, name, role) {
let match = employees.find(e => e.name === name);
if (match) {
match.role = [...new Set(match.role.concat(role))];
} else {
match = { name, role };
}
return match;
}
let employees = [{"name":"Joe","role":["Admin","Developer"]},{"name":"Sherry","role":["Analyst","QA-tester"]}];
let result = addRoles(employees, "Sherry", ["Manager", "QA-tester"]);
console.log(result);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments