如何实现支持对象数组与单个对象的通用映射函数以消除代码重复
Great question! Having duplicate mapping logic across two functions is definitely something we can fix with a simple, reusable approach. The key idea is to extract the core object transformation into a single helper function, then have our universal handler decide whether to apply it to an array or a single object.
Step 1: Extract the Reusable Mapping Logic
First, let's pull out the logic that transforms a single object into your desired format—this eliminates duplication entirely:
const mapSingleItem = (item) => ({ title: `${item.first_name} ${item.last_name}`, subTitle: item.city, id: item.id });
Note: Your original mapSelectedItem used Object.keys().reduce() which was unnecessary for a single object—we can directly return the transformed object instead, making the code simpler.
Step 2: Build the Universal Function
Now create a single function that checks if the input is an array or a single object, then applies our helper accordingly:
const fake = [ { city: 'TOLEDO', first_name: 'Bob', id: 5, last_name: 'KHALIL' }, { city: 'TOLEDO', first_name: 'Boby', id: 6, last_name: 'KHALIL' }, { city: 'TOLEDO', first_name: 'Boby', id: 7, last_name: 'KHALIL' } ]; export function mapUniversalData(uiData) { if (Array.isArray(uiData)) { return uiData.map(mapSingleItem); } // Handle single object case return mapSingleItem(uiData); }
How It Works
- If you pass an array (like
fake), it usesArray.map()to applymapSingleItemto every element, returning an array of transformed objects. - If you pass a single object (like
fake[0]), it directly returns the transformed object matching your desired format.
Testing It Out
// Test array input console.log(mapUniversalData(fake)); // Output: Array of 3 objects with title, subTitle, id properties // Test single object input console.log(mapUniversalData(fake[0])); // Output: { title: "Bob KHALIL", subTitle: "TOLEDO", id: 5 }
This approach keeps your code DRY (Don't Repeat Yourself), is easy to maintain, and handles both input types with minimal overhead.
内容的提问来源于stack exchange,提问作者Palaniichuk Dmytro

