如何在JavaScript中合并数组内属性相同的对象并转换唯一属性为数组?
Merge Objects with Identical Properties in JavaScript
Great question! Here's a practical, flexible way to achieve this in JavaScript, perfectly suited to your example:
function mergeSimilarObjects(arr) { // Temporary object to group matching objects const groupedObjects = {}; arr.forEach(obj => { // Create a unique key based on properties that should be identical (color + shape here) const groupingKey = `${obj.color}-${obj.shape}`; if (!groupedObjects[groupingKey]) { // Initialize the group with a copy of the current object groupedObjects[groupingKey] = {...obj}; } else { // Merge differing properties into arrays Object.keys(obj).forEach(prop => { if (groupedObjects[groupingKey][prop] !== obj[prop]) { // Convert existing value to array if it isn't already if (!Array.isArray(groupedObjects[groupingKey][prop])) { groupedObjects[groupingKey][prop] = [groupedObjects[groupingKey][prop]]; } // Add the new unique value groupedObjects[groupingKey][prop].push(obj[prop]); } }); } }); // Convert the grouped object back to an array of merged objects return Object.values(groupedObjects); } // Test with your sample input const input = [ {color:'red', shape:'circle', size:'medium'}, {color:'red', shape:'circle', size:'small'} ]; console.log(mergeSimilarObjects(input)); // Output: [ { color: 'red', shape: 'circle', size: ['medium', 'small'] } ]
How this works:
- Grouping logic: We generate a unique key using the properties that define a "matching" object (in your case,
colorandshape). This ensures we only combine objects that are truly duplicates in those core properties. - Initialize new groups: When we encounter an object that doesn't belong to an existing group, we add it to our temporary storage as a new entry.
- Merge unique properties: For objects in an existing group, we check each property. If the value is different, we convert the property to an array (if it's not already one) and append the new value.
- Final array conversion: We extract the values from our temporary grouped object to get the final array of merged objects.
Customization tip:
To make this function work for any set of grouping properties, you can modify it to accept an array of keys to group by:
function mergeSimilarObjects(arr, groupingProps) { const groupedObjects = {}; arr.forEach(obj => { // Dynamic key based on provided properties const groupingKey = groupingProps.map(prop => obj[prop]).join('-'); // Rest of the merging logic stays the same... }); return Object.values(groupedObjects); } // Usage example: group by 'color' and 'shape' mergeSimilarObjects(input, ['color', 'shape']);
This makes the function reusable for all kinds of merging scenarios!
内容的提问来源于stack exchange,提问作者Gokkul
相关产品推荐
相关产品推荐

