1

I'm struggling with array manipulation when they are arrays of different types. My problem is rather simple, but I would still appreciate any assistance.

I have the following two classes:

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

I have two arrays:

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

The array of Group is populated 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 a uId that is accessible through the active route in Angular (for this example it can just be a local variable):

currentUserID = 1;

What I want to be able to do is push each gId of the array of Group into the array of UserGroup while appending currentUserId as the uId.

The final result should look something like:

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

3 Answers 3

2

You can use Array#map.

const arr = [{gId: 1, gName: "Manager"},
{gId: 2, gName: "Nurse"},
{gId: 3, gName: "Audit"}];
let currentUserID = 1;
const res = arr.map(({gId})=>({gId, uId: currentUserID}));
console.log(res);

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

Comments

1
const finalUserGroupsToUpdate: UserGroup[];
const pickListUserAssociatedGroups: Group[] =[{gId: 1, gName: "Manager"},
{gId: 2, gName: "Nurse"},
{gId: 3, gName: "Audit"}];

const currentUserID = 1;
pickListUserAssociatedGroups.forEach(({gId}) => {
  finalUserGroupsToUpdate.push({gId, uId: currentUserID})
});

console.log(finalUserGroupsToUpdate);

Comments

1

Say, you have your groups in arrayOfGroups and you want to assign each group id gId to current user id uId and hold them in array arrayOfUserGroups.

currentUserID = 1;
arrayOfUserGroups = [];


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

1 Comment

Please explain your answer so that it is easy for others to understand why this might work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.