如何用ES6简洁的不可变函数式方法按type字段分组数组对象?
type Field Absolutely! You can pull this off neatly with ES6's Array.prototype.reduce() paired with spread syntax to keep everything immutable—no sneaky mutations of your original array or objects. Let's walk through this with your sample data (first, quick note: your sample JSON has a missing closing } on the last object; I'll fix that in the example below).
Step-by-Step Solution
Here's a concise, functional approach that preserves immutability:
const accounts = [ {"account": {"name": "Bob's credit", "type": "credit", "id": "1"}}, {"account": {"name": "savings", "type": "savings", "id": "2"}}, {"account": {"name": "vacation savings", "type": "savings", "id": "3"}}, {"account": {"name": "son's savings", "type": "savings", "id": "4"}}, {"account": {"name": "wife's credit card", "type": "credit", "id": "5"}} // Fixed missing closing brace ]; const groupedByType = accounts.reduce((acc, item) => { const accountType = item.account.type; return { ...acc, [accountType]: [...(acc[accountType] || []), item.account] }; }, {});
How This Works
- Immutability First: Instead of modifying the accumulator (
acc) directly, we use the spread operator (...) to create a brand new object every iteration. This ensures your originalaccountsarray and its nested objects stay untouched. - Dynamic Key Handling:
[accountType]uses computed property names to target the correct group for each item automatically. - Safe Group Initialization:
...(acc[accountType] || [])checks if the group already exists—if not, it starts with an empty array before adding the current account, avoiding undefined errors.
Expected Output
Running the code above will give you this clean grouped structure:
{ credit: [ {"name": "Bob's credit", "type": "credit", "id": "1"}, {"name": "wife's credit card", "type": "credit", "id": "5"} ], savings: [ {"name": "savings", "type": "savings", "id": "2"}, {"name": "vacation savings", "type": "savings", "id": "3"}, {"name": "son's savings", "type": "savings", "id": "4"} ] }
If you want to keep the outer account key in each grouped item (instead of extracting the inner object), just tweak the line to [accountType]: [...(acc[accountType] || []), item]—the rest of the logic stays identical!
内容的提问来源于stack exchange,提问作者chrisl-921fb74d

