What is the best way to add an array value into an object?

I'm looking to build an object comprised of nested arrays that will resemble the following structure:

[{"name":"Joe","role":["Admin","Developer"]},{"name":"Sherry","role":["Analyst","QA-tester"]}]

My goal is to be able to access and modify the roles array for a specific individual, like Sherry, by adding additional values. How can I achieve this?

employees = [];

// [*retrieve names and associated roles from database*]

employees.push({name: exampleVar1, role: exampleVar2});

Desired outcome: I aim to save names in order to append corresponding roles for each employee, then utilize this object as a point of reference later on.

Answer №1

You have the option of utilizing Array.find(....) function to locate the specific object that requires additional roles. Below is a practical demonstration:

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

Answer №2

To handle unique names, one solution is to utilize a Map in JavaScript for efficient management.

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

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

You can retrieve roles by using get with the respective name as the key:

const roles = dataMap.get('Sherry')

From there, you have the flexibility to add or remove roles from the returned array using push or pop.

If you prefer not to use a Map, an alternative approach is utilizing the Array's map method:

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)

Answer №3

To efficiently manage employee roles, you can implement a function that locates the employee in the database (or creates a new entry if not found), assigns the specified role(s), and ensures duplicate roles are avoided:

function updateEmployeeRoles(employees, name, role) {
  let match = employees.find(e => e.name === name);
  if (match) {
    match.role = [...new Set(match.role.concat(role))]; // Add new roles
  } else {
    match = { name, role }; // Create new entry for employee
  }
  return match;
}

let employees = [{"name":"Joe","role":["Admin","Developer"]},{"name":"Sherry","role":["Analyst","QA-tester"]}];

let result = updateEmployeeRoles(employees, "Sherry", ["Manager", "QA-tester"]);

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to save data to a file using React?

As I work on a React web application, the need has arisen to store crucial user data on the client side in a stable manner. Due to the requirement of data stability and the constraint against using Indexed DB, I am considering storing the data as JSON in ...

What is the best way to manage undefined status in react after the user chooses to cancel selecting a file?

Having an issue with my simple Input file type in React. I'm storing the selected file in state, but when I click the clear button, the state doesn't actually get cleared. This leads to {selectedFile.name} throwing an undefined error if the user ...

Can a file be transferred from an Electron application to an Express server by supplying the file path?

This is my current objective: A user drags and drops a file into Electron Electron uses a python script via child_process.exec to convert the file The conversion process generates a new file in the same directory as the original With knowledge of the path ...

Internet Explorer does not automatically resend AJAX requests after submitting a form

Specifically mentioning IE in my title because my code functions correctly on Chrome. The "Maintenance" view I have is responsible for creating, editing, and deleting. The form is located in a partial view named "_MaintenanceForm" with its own GET/POST met ...

Is there a way for me to dynamically retrieve the input value produced by the Query?

Is there a way to retrieve the value of a dynamically created input field? $('#inputArea').append(" <input id = "arrivalTime1" type = 'number' placeholder='Arrival Time' style = 'display: none;'> " ...

When using Node.js, React.js does not recognize raw HTML strings as valid HTML elements

I successfully sent raw HTML from node.js to react, but when I try to render it, the content is displayed as a raw string instead of HTML elements. This is how I retrieve the string in the front-end: componentDidMount() { this.callApi() .then( ...

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

Having trouble with Angular 2's Output/emit() function not functioning properly

Struggling to understand why I am unable to send or receive some data. The toggleNavigation() function is triggering, but unsure if the .emit() method is actually functioning as intended. My end goal is to collapse and expand the navigation menu, but for ...

The functions isModified and isNew in Mongoose

In various tutorials, I have come across this particular example and it has raised a question in my mind. I am curious as to why this works with new documents. Could it be that new documents are automatically considered modified? Wouldn't it make more ...

Utilizing document.getSelection() for extracting data into an array, similar to how document.getSelection().toString() functions for handling strings

In my Angular JS application, I have a table with filtering functionality. I need to extract only the selected data from the table and store it in an array of arrays called "rows[]" and "cell[]". This makes it challenging to just export the entire table da ...

Is there a way to integrate the AJAX response from JavaScript into a JavaScript function?

I am having a nightmare trying to solve this issue. I am currently working on an app using phonegap and have integrated highcharts for creating graphs. The graph displays properly, but the tooltip is not working as expected. Below is the code snippet that ...

Using ng-options to connect an array of objects to an ng-init attribute

Working on creating a select dropdown using ng-options to iterate over an array of objects and linking it to ng-init. However, running into an issue where the correct variable needs to be passed through ng-change as well. The current code is set up in a w ...

Quick method for updating the contents of an array

Is there a way to replace the content of an array and still maintain a reference to it without losing the original reference? I want to avoid simply reassigning the array like this: var arr1 = [1,2,3]; var referenceToArr1 = arr1; var arr2 = [4,5,6]; arr1 ...

Having issues with AngularJS rzslider failing to dispatch updated slider value

Hello, I am currently using the rzmodule/rzslider in AngularJS. However, after changing the slider to a specific range, the ng-modal is not returning the updated value. It keeps returning the initial value of 10000 that was configured initially. $scope.sl ...

Class components in React can also utilize the `useSelector` hook from Redux. Here's a guide on how to

How can I access data from my Redux store without encountering any errors? For function-based components, I typically use the following method: ... import { useSelector } from 'react-redux'; export default function App(...){ ... const som ...

Using the "margin: auto" property to center the text box

I am having trouble centering the search box. I tried adding marginLeft: "auto",marginRight: "auto" to the search class but it's not working. Can you please advise me on how to fix this issue? Below is my code snippet and a link to the sandbox: https ...

When utilizing the `express.static(__dirname)` function in Node.js with Express, the visitor may be directed to an incorrect HTML page

My website consists of a login page named login.html and an index page named index.html. I want to implement authentication so that only logged in users can access the index page. I have not set up the post method on the login HTML page. Therefore, I have ...

Unchanging Dive Field

I'm having trouble understanding why this field isn't updating with the correct number. It seems that any value less than 1 is being rounded in the alert() function. I believe all numbers are simply getting rounded down, but I'm unsure of an ...

Employ the Google Charting library for creating a GeoChart that is currently not displaying

Hello everyone. I'm having a bit of an issue with my web page development. I've been trying to add a GeoChart, but no matter how many times I copy-paste the code from the Google developer's website, the map just won't show up. I must be ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...