TypeScript中如何复制对象列表?复制后变量无值问题求助
all and available Variables in Your Dual Box Setup Hey there! Let's dig into why your all and available variables are ending up empty, and fix the array copying issue you're facing. From your code, I see a few key areas we need to check and adjust:
1. Potential Issues Causing Empty Variables
a. API Response Structure & Missing Error Handling
When projectId is defined, you're fetching data with await this.restful.get(...)—but many REST APIs wrap their response data in a data property (e.g., { data: [...] }). If you're calling .map() directly on the full response object instead of the actual array inside it, you'll get an empty or invalid all variable. Also, you’re not handling cases where the API request fails, which would leave projectTeamId undefined entirely.
b. No Matches in this.allUser
Your map call relies on this.allUser.find(allUser => allUser.key == id)—if none of the ids from projectTeamId match entries in this.allUser, you’ll end up with an array full of undefined values, which might look "empty" when logged.
c. Uninitialized this.allUser
When projectId is undefined, you’re copying this.allUser—if this.allUser hasn’t been properly initialized (e.g., it’s undefined or an empty array), all will naturally be empty too.
2. Fixes & Improved Code
Let's adjust your function to address these issues step by step:
protected async processMoverBox(projectId?: number) { let available: any[] = []; // Initialize with empty array to avoid undefined let all: any[] = []; try { if (projectId !== undefined) { // Fetch project team IDs, and ensure we access the correct data property (adjust if your API uses a different key) const apiResponse = await this.restful.get(`api/operation/S200100/allprojectteam/${projectId}`); const projectTeamId = apiResponse.data || []; // Fallback to empty array if data is missing console.log('Project Team IDs:', projectTeamId); // Map and filter out any undefined entries (in case no match is found in allUser) all = projectTeamId .map(id => this.copy(this.allUser.find(allUser => allUser.key === id))) .filter(Boolean); // Remove undefined values } else { // Ensure this.allUser is an array before copying all = this.allUser ? this.copy([...this.allUser]) : []; console.log('All Users:', this.allUser); } console.log('Final all array:', all); // Copy all to available (use the actual all array instead of test data) available = [...all]; // Shallow copy works if objects don't need deep cloning; use this.copy if deep clone is needed // Remove selected items from available if (this.selected.length > 0) { this.selected.forEach(ms => { const index = available.findIndex(e => e.key === ms.key); if (index !== -1) { // Only splice if the item exists available.splice(index, 1); } }); } console.log('Available after removing selected:', available); console.log('Selected items:', this.selected); this.memberDualbox.initMoveBox(available, this.selected, all); this.memberDualbox.disabled = this.isViewMode; } catch (error) { // Handle API errors or unexpected issues console.error('Error processing mover box:', error); } }
Key Changes Explained:
- Initialize variables: Start
availableandallwith empty arrays to avoidundefined-related bugs. - API response safety: Explicitly access the
dataproperty (adjust if your API uses a different structure) and fallback to an empty array if the response is missing data. - Filter invalid entries: Use
.filter(Boolean)to remove anyundefinedvalues from the mappedallarray. - Safe copying: Ensure
this.allUserexists before copying it, and use spread syntax ([...this.allUser]) for shallow copies (stick with yourthis.copyfunction if you need deep cloning of nested objects). - Error handling: Wrap async logic in a
try/catchblock to catch and log unexpected issues like API failures. - Safe splice: Check if the index exists before calling
spliceto avoid errors when the selected item isn’t inavailable.
3. Quick Note on Array Copying
For shallow copies of arrays (where you don’t need to clone nested objects), all these methods work reliably:
available = [...all]available = all.slice()available = Array.from(all)
If you need deep copies (because your user objects have nested properties), make sure your this.copy function properly clones those nested structures—otherwise, changes to objects in available might affect all and vice versa.
内容的提问来源于stack exchange,提问作者Bunpot Darawankul

