如何拼接数据库中姓名列?遇Cannot read property 'firstName' of null及数据重复问题
How to Fix Name Concatenation, Null Error, and Duplicate Data Issues
Hey there! Let's tackle your problems one by one—sounds like you've got a few kinks to work out with your locker data:
1. Fixing the Cannot read property 'firstName' of null Error
This error pops up because not all lockers are assigned to students, so some entries have a null value for the student field. When you try to access student.firstName directly on a null, JavaScript throws that error.
Quick Fixes:
- Use the optional chain operator (
?.) to safely access nested properties:// Basic concatenation with safety check const fullName = `${locker.student?.firstName || ''} ${locker.student?.lastName || ''}`.trim(); - For cleaner handling (avoids extra spaces if a name field is empty), filter out falsy values first:
// Join only non-empty name parts const fullName = locker.student ? [locker.student.firstName, locker.student.lastName].filter(Boolean).join(' ') : 'Unassigned'; // Show this if no student is assigned
2. Resolving Duplicate Data Showing 4 Times
Seeing duplicate entries usually means your API request is being called multiple times, or your component is re-rendering and re-fetching data unnecessarily.
Common Fixes:
- Check your request trigger: If you're using a framework like React, make sure your fetch call is wrapped in a
useEffectwith an empty dependency array ([])—this ensures it only runs once on component mount:useEffect(() => { const fetchLockers = async () => { const res = await fetch('/api/lockers'); let data = await res.json(); // Deduplicate data (use your locker's unique identifier, e.g., id) const uniqueLockers = Array.from(new Map(data.map(locker => [locker.id, locker])).values()); console.log(uniqueLockers); // No more duplicates! }; fetchLockers(); }, []); // Empty array = run once - Deduplicate manually: If you can't fix the repeated requests, you can always clean the data after fetching using a
Map(as shown above) or aSetto keep only unique entries.
Putting It All Together
Here's a full example that handles both the null error and duplicate data:
async function getProcessedLockers() { const response = await fetch('/api/lockers'); let rawData = await response.json(); // Remove duplicates const uniqueData = Array.from(new Map(rawData.map(item => [item.id, item])).values()); // Process each locker to add full name return uniqueData.map(locker => ({ ...locker, studentFullName: locker.student ? [locker.student.firstName, locker.student.lastName].filter(Boolean).join(' ') : 'Unassigned' })); } // Usage getProcessedLockers().then(processedLockers => { console.log(processedLockers); });
内容的提问来源于stack exchange,提问作者Curious-programmer
相关产品推荐
相关产品推荐

