如何用JavaScript实现类似MySQL GROUP_CONCAT的按属性分组拼接
type and Concatenate description Got it, let's break down how to replicate MySQL's GROUP_CONCAT behavior in JavaScript for your array—grouping objects by their type and stitching together the description fields with commas. Here are a couple of straightforward solutions:
Basic Solution (includes duplicate descriptions)
The Array.reduce() method is perfect for this kind of grouping and aggregation. It lets us build up a result object where keys are the type values, and values are the concatenated description strings.
let obj = [ { "type": "Bedroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test" }, { "type": "Bedroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test1" }, { "type": "Bedroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Test" }, { "type": "Bathroom", "int_input": 1, "enum_input": 0, "enum_select": "Yes", "description": "Sink leak" } ]; const grouped = obj.reduce((acc, currentItem) => { // If the type isn't in our accumulator yet, initialize it with the current description if (!acc[currentItem.type]) { acc[currentItem.type] = currentItem.description; } else { // Append the new description with a comma separator acc[currentItem.type] += `, ${currentItem.description}`; } return acc; }, {}); console.log(grouped); // Output: // { // Bedroom: "Test, Test1, Test", // Bathroom: "Sink leak" // }
Solution with Deduplicated Descriptions
If you want to avoid repeating the same description (like the duplicate "Test" in the Bedroom group), we can use a Set to track unique values before joining them:
const groupedUnique = obj.reduce((acc, currentItem) => { if (!acc[currentItem.type]) { // Use a Set to automatically handle unique descriptions acc[currentItem.type] = new Set(); } acc[currentItem.type].add(currentItem.description); return acc; }, {}); // Convert the Sets back to comma-separated strings const finalResult = Object.fromEntries( Object.entries(groupedUnique).map(([type, descSet]) => [type, Array.from(descSet).join(', ')]) ); console.log(finalResult); // Output: // { // Bedroom: "Test, Test1", // Bathroom: "Sink leak" // }
Optional: Convert to Array of Objects
If you prefer the result as an array of objects (instead of a plain key-value object), you can transform the final output like this:
const resultArray = Object.entries(grouped).map(([type, description]) => ({ type, description })); console.log(resultArray); // Output: // [ // { type: "Bedroom", description: "Test, Test1, Test" }, // { type: "Bathroom", description: "Sink leak" } // ]
内容的提问来源于stack exchange,提问作者learner

