push()函数覆盖数组末项及对象数组去重添加逻辑咨询
Hey there! Let's break down your problems one by one and fix them up with clear, actionable code.
1. Fixing the push() Overwriting the Last Array Item
This is almost always caused by reusing the same object reference instead of creating a new instance each time you add to the array. Since objects are reference types, every time you push that single object to the array and modify its properties, all entries in the array point to the same object—so every entry ends up reflecting the last set of changes.
Example of the Problem
// Wrong approach: reusing the same object const group = { name:"", code:"" }; const groupList: any[] = []; // Simulating multiple additions group.name = "Group 1"; group.code = "G1"; groupList.push(group); group.name = "Group 2"; group.code = "G2"; groupList.push(group); console.log(groupList); // Both entries will be { name: "Group 2", code: "G2" }
The Fix: Create New Objects Each Time
Instead of reusing the same object, create a fresh instance every time you need to add a new entry. You can do this directly with object literals, or use a factory function for reusability:
// Correct approach: create new objects const groupList: any[] = []; // Option 1: Use object literals directly groupList.push({ name: "Group 1", code: "G1" }); groupList.push({ name: "Group 2", code: "G2" }); // Option 2: Factory function for consistent object creation const createGroup = (name: string, code: string) => ({ name, code }); groupList.push(createGroup("Group 1", "G1")); groupList.push(createGroup("Group 2", "G2"));
2. Implementing Existence Checks & Cross-Array Associations
Let's build out your expected logic step by step: first checking if an object exists before adding it, then associating ej's business group data with groupList.
Step 1: Reusable Helper Functions for Existence Checks
We'll use code as the unique identifier (adjust this if you need to check against name or a combination of properties):
// Check if a group exists in groupList by code const groupExists = (targetCode: string) => groupList.some(group => group.code === targetCode); // Check if an ej exists in ejList by code const ejExists = (targetCode: string) => ejList.some(ej => ej.code === targetCode);
Step 2: Add to groupList with Existence Check
const addToGroupList = (group: { name: string, code: string }) => { if (!groupExists(group.code)) { groupList.push({ ...group }); // Spread operator creates a new object copy (avoids reference issues!) console.log(`Added new group: ${group.name}`); } else { console.log(`Group with code ${group.code} already exists`); } };
Step 3: Add to ejList + Associate Business Group to groupList
const addToEjList = (ej: { name: string, code: string, namebusinessG: string, codebusinessG: string }) => { if (!ejExists(ej.code)) { ejList.push({ ...ej }); // Spread to add a copy of the ej object console.log(`Added new ej: ${ej.name}`); // Add the associated business group to groupList (if not already present) const businessGroup = { name: ej.namebusinessG, code: ej.codebusinessG }; addToGroupList(businessGroup); } else { console.log(`Ej with code ${ej.code} already exists`); } };
Example Usage
// Initialize your arrays let groupList: any[] = []; let ejList: any[] = []; // Test adding a group (and duplicate) addToGroupList({ name: "Admin Team", code: "ADMIN" }); addToGroupList({ name: "Admin Team", code: "ADMIN" }); // Logs that it already exists // Test adding an ej and its associated business group addToEjList({ name: "Sales Department", code: "SALES_EJ", namebusinessG: "Sales Group", codebusinessG: "SALES" }); // View the final results console.log(groupList); // Contains ADMIN and SALES groups console.log(ejList); // Contains SALES_EJ
Key Notes
- The spread operator (
...) ensures we're pushing a copy of the object, not the original reference—this prevents the first issue (overwriting items) from happening here too. some()is efficient for existence checks because it stops searching as soon as it finds a match.
内容的提问来源于stack exchange,提问作者infodev

