Issue
I want to move a value on one array to another. Here's the first array
"availableMember": [
{
"id": 18,
"userDivisionId": 1,
"userDivisionCode": "1",
"userDivisionName": "DEPT. MARKETING & LOGISTIK"
},
{
"id": 26,
"userDivisionId": 333,
"userDivisionCode": "2.3.21.02",
"userDivisionName": "YGY PO"
},
{
"id": 27,
"userDivisionId": 335,
"userDivisionCode": "2.3.21.02.04",
"userDivisionName": "YGY MO"
},
]
and I want to move, for example object with userDivisionId is 333, to the second array.
"selectedMember": []
I already try using .splice(), but sometimes its work and sometimes it doesn't. Any idea how to do this? Please help me.
Thank you.
Solution
Array.find() is the most appropriate method. It takes a function as a parameter and will return the first element in which the function returns true. If you want to find all occurrences, just substitute find with filter. Use Array.push() to add an element to an array, or Array.concat() to concatenate two arrays.
availableMember = [
{
id: 18,
userDivisionId: 1,
userDivisionCode: '1',
userDivisionName: 'DEPT. MARKETING & LOGISTIK',
},
{
id: 26,
userDivisionId: 333,
userDivisionCode: '2.3.21.02',
userDivisionName: 'YGY PO',
},
{
id: 27,
userDivisionId: 335,
userDivisionCode: '2.3.21.02.04',
userDivisionName: 'YGY MO',
},
];
selectedMember: any[] = [];
Adding a single element
ngOnInit(): void {
const selected = this.availableMember.find(
(el) => el.userDivisionId === 333
);
this.selectedMember.push(selected);
}
Adding multiple elements
ngOnInit(): void {
const selected = this.availableMember.filter(
(el) => el.userDivisionId === 333 || el.userDivisionId === 335
);
this.selectedMember = this.selectedMember.concat(selected);
}
Answered By - Chris Hamilton
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.