4

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.

2
  • okay so what is the issue? Commented Sep 5, 2019 at 17:27
  • The issue is adding additional roles to Sherry or Joe. Commented Sep 5, 2019 at 17:55

3 Answers 3

4

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);

Sign up to request clarification or add additional context in comments.

Comments

3

Assuming your names are unique, I'd use a Map for this kind of thing.

const data = [{ name: 'Joe', role: ['Admin', 'Developer'] }, { name: 'Sherry', role: ['Analyst', 'QA-tester'] }]

/// create your Map
const dataMap = new Map()
data.forEach(d => dataMap.set(d.name, d.role))

Access the roles using get with the name as your key:

const roles = dataMap.get('Sherry')

Then you can push or pop roles in or out of the array that gets returned.

If you'd rather not use a Map then the other sort of map would work too:

const data = [{ name: 'Joe', role: ['Admin', 'Developer'] }, { name: 'Sherry', role: ['Analyst', 'QA-tester'] }]

const updatedData = (nameToUpdate, newRole) =>
 data.map(d => d.name === nameToUpdate? {...d,role: [...d.role, newRole]}:d)

Comments

1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.