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 can use Array.find(....) to find the object that you want to add roles to, here is an example:
const arr = [{"name":"Joe","role":["Admin","Developer"]},{"name":"Sherry","role":["Analyst","QA-tester"]}]
const nameToFind = 'Sherry';
const newRole = 'Admin';
const found = arr.find(({ name }) => name === nameToFind);
if (found) {
found.role.push(newRole);
}
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With