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

JavaScript合并数组时为重复属性添加前缀的技术实现问询

Merge Arrays with Prefixes to Avoid Overwriting Duplicate Properties

Got it, let's fix this so you preserve all properties from both arrays without overwriting duplicate keys—adding prefixes to each dataset's attributes is the perfect approach here. Here's a step-by-step solution tailored to your scenario:

1. Create a Reusable Prefix Helper Function

First, make a small function to add a prefix to all properties of an object (we'll keep the id as-is since that's our matching key):

function addPrefixToObject(obj, prefix) {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    // Keep id unchanged, attach prefix to every other property
    acc[key === 'id' ? key : `${prefix}_${key}`] = value;
    return acc;
  }, {});
}

2. Apply Prefixes to Both Arrays

Use the helper to transform each array's objects, ensuring their property names become unique:

// Add "a_" prefix to all aData properties except id
const prefixedA = aData.map(item => addPrefixToObject(item, 'a'));
// Add "b_" prefix to all bData properties except id
const prefixedB = bData.map(item => addPrefixToObject(item, 'b'));

3. Merge the Prefixed Arrays Safely

Now you can merge them using reduce without worrying about overwrites—all property names are distinct now:

// Merge objects by their id, combining all prefixed properties
const mergedById = [...prefixedA, ...prefixedB].reduce((acc, item) => {
  const id = item.id;
  // Combine existing entry (if it exists) with the current prefixed item
  acc[id] = { ...(acc[id] || {}), ...item };
  return acc;
}, {});

// Optional: Convert the merged object back to an array if you need array format
const mergedArray = Object.values(mergedById);

Example Result

For your sample data, the merged object for id: 1 will look like this:

{
  id: 1,
  a_title: 'title',
  a_code: '34x',
  b_prop: 3,
  b_otherprop: 'prop',
  b_code: 'hi67'
}

Quick Customization Tips

  • If you want more descriptive prefixes (like sourceA_ instead of a_), just pass a different string to the addPrefixToObject function.
  • If you ever need to include id in the prefix (unlikely here since we use it for matching), just remove the key === 'id' check from the helper function.

内容的提问来源于stack exchange,提问作者Sergino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:34:27