Reputation: 129
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}
Upvotes: 1
Views: 65
Reputation: 2131
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});
});
Upvotes: 1
Reputation: 912
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);
Upvotes: 1
Reputation: 89517
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);
Upvotes: 2