You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现支持对象数组与单个对象的通用映射函数以消除代码重复

Clean Up Duplicate Mapping Logic with a Universal Function

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 uses Array.map() to apply mapSingleItem to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:14:07