Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help.

Here are the two interfaces I'm using:

export interface Group {
  gId: number;
  gName: string;
}
export interface UserGroup {
  uId: number;
  gId: number;
}

I currently have two arrays:

finalUserGroupsToUpdate: UserGroup[];
pickListUserAssociatedGroups: Group[];

The Group array is already filled and looks like this in the console:

(3) [{...}, {...}, {...}]
0: {gId: 1, gName: "Manager"}
1: {gId: 2, gName: "Nurse"}
2: {gId: 3, gName: "Audit"}

I also have access to uId through the active route in Angular (for this example, it can be treated as a local variable):

currentUserID = 1;

My goal is to push each gId from the Group array into the UserGroup array while adding currentUserID as the uId.

The desired final outcome should resemble:

(3) [{...}, {...}, {...}]
0: {gId: 1, uId: 1}
1: {gId: 2, uId: 1}
2: {gId: 3, uId: 1}

Answer №1

You could utilize the Array#map method for this task.

const list = [{id: 1, name: "John"},
{id: 2, name: "Sarah"},
{id: 3, name: "Ethan"}];
let currentUserId = 1;
const result = list.map(({id})=>({id, userId: currentUserId}));
console.log(result);

Answer №2

let updatedGroups: UserGroup[];
const associatedGroups: Group[] = [{gId: 1, gName: "Supervisor"},
{gId: 2, gName: "Doctor"},
{gId: 3, gName: "Analyst"}];

const userID = 1;
associatedGroups.forEach(({gId}) => {
  updatedGroups.push({gId, uId: userID});
});

console.log(updatedGroups);

Answer №3

Assume you have an array of groups stored in the variable arrayOfGroups. You wish to assign each group's id, represented by gId, to the current user's id, denoted by uId, and store this information in a new array called arrayOfUserGroups.

currentUserID = 1;
arrayOfUserGroups = [];


arrayOfGroups.forEach(group => {
    arrayOfUserGroups.push({gId: group.gId, uId: currentUserID});
});

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

Encountering an issue when trying to submit the form - "Cannot POST /public/register-controller

I am currently working on developing a login/signup system using Express.js, MySQL, and Node.js. However, I encountered an error when I clicked on the submit button: Cannot POST /public/register-controller This is my index.html: <!DOCTYPE html> ...

Extract the array of numbers from the JSON file

My task is to extract an array of numbers from JSON files. I need to handle files that contain only arrays of numbers or one level deeper (referred to as direct arrays). These files may also include other data types such as strings or booleans. The challe ...

Utilizing CSS, Javascript, and Jquery to Toggle a DIV's Visibility Based on Clicking Either of Two Images

Need help with showing and hiding divs based on image clicks. Have 2 images (Image_A and Image_B) and 2 hidden Divs (Div_A and Div_B). If Image_A is clicked, show Div_A. If Image_B is clicked, hide Div_A and show Div_B. This should work both ways, ensurin ...

Discovering the ways to retrieve Axios response within a SweetAlert2 confirmation dialog

I'm struggling to grasp promises completely even after reviewing https://gist.github.com/domenic/3889970. I am trying to retrieve the response from axios within a sweetalert confirmation dialog result. Here is my current code: axios .post("/post ...

Tips on tallying the frequency of items in a state array

I'm currently working on an application in which clicking a button adds the item's value to the state. The button is clickable multiple times, allowing the same item to be added multiple times in the state array. My current code snippet: export ...

How can one determine the data type by analyzing the key value?

I'm attempting to determine the return type of getAllRaces() as () => Race[]. Here is what I have tried so far: type CollectionMap = { races: Race[] horses: Horse[] } type Race = { date: Date } type Horse = { name: string } typ ...

Hey there everyone, I was wondering how to send both single and multiple values to a database using JavaScript and JSON endpoints with a Spring Web API

{ "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date&q ...

Interface of TypeScript Undetermined

Currently, I am developing a Demo API Wrapper specifically for Roblox. During the development process, I have come across a certain issue that I would like to address. My aim is to send a request and then return all the data in the manner of an API wrapper ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Looking to implement client-side JavaScript validation prior to utilizing jQuery AJAX validation

I'm struggling to make sure that my validate(form) function runs "before" my ajax function. I would appreciate any suggestions on how to connect the two and ensure they run in sequence when the form is submitted. Thank you! <script type="text/ ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Several iFrames embedded on the website automatically adjust to the same pre-set height

Apologies if this question has already been addressed, but I am struggling to properly articulate it. Here's the issue: I have a client's holiday accommodation website that uses three embedded iFrames for a Calendar, Booking Enquiry, and floorpla ...

Connecting multiple promises using an array

After making an ajax call to retrieve an array of results, I have been attempting to process this data further by making additional ajax calls. However, when using Promise.all() and then continuing with .then(function(moreData){}), I noticed that the moreD ...

Updating a Mongoose document without overwriting existing values using FindOneAndUpdate

I have the following schema: { guildId: { type: String, required: true, unique: true }, systems:{ reactChat:{ type: Array, required: true, ...

Failure to receive a server response during the AJAX communication

I am facing an issue with my code that is making 3 requests to a server. The code successfully sends the request, but fails when receiving the response. I need help in skipping the first response and only getting the third one. phone.open("POST", '/& ...

Dealing with non-string values (such as Date, Double, Boolean) when creating JSON through iterative mapping with Map and Object Array in Scala

How can I handle non-string values (Date, Double, Boolean) when building JSON in Scala by looping with Map and Object Array? In the following example, I always end up with non-string values as strings in the Values Array. import play.api.libs.json._ impor ...

Employing 'as' in a similar manner to *ngIf

Utilizing the *ngIf directive, one can simplify code by assigning a property from an observable using syntax like *ngIf = (value$ | async).property as prop . This allows for the use of prop throughout the code without repeated references to (value$ | async ...

Is there a list (collection) feature in nodejs similar to that in Java?

Is there a list collection type concept in nodejs similar to dynamic arrays? I need this kind of dynamic array functionality for my nodejs coding. Are there any concepts such as list or something similar available in nodejs? My code snippet is provided ...

What to do when your Numpy array exceeds RAM capacity: Store to disk or use an out-of-core approach?

In my workflow, I have a process where I add data to an initial pandas Series object. This empty array could also be a NumPy array, or a simple list. in_memory_array = pd.Series([]) for df in list_of_pandas_dataframes: new = df.apply(lambda row: comp ...

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...