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 ofa_), just pass a different string to theaddPrefixToObjectfunction. - If you ever need to include
idin the prefix (unlikely here since we use it for matching), just remove thekey === 'id'check from the helper function.
内容的提问来源于stack exchange,提问作者Sergino
相关产品推荐
相关产品推荐

