Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert array value into object?

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.

like image 914
rsenecaljr Avatar asked Jan 25 '23 21:01

rsenecaljr


1 Answers

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);
like image 73
Titus Avatar answered Jan 28 '23 09:01

Titus