是否有一种简洁的 es6 功能方法可以按类型对项目进行分组,因为它是不可变的?
accounts.json
[
{"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": "savings", "id": "5"}
]
预计
[
{"savings": [
{"account": {"name": "savings", "type": "savings", "id": "2"}},
{"account": {"name": "vacation savings", "type": "savings", "id": "3"}},
{"account": {"name": "son's savings", "type": "savings", "id": "4"}
]},
{"checking": [
{"account": {"name": "wife's credit card", "type": "savings", "id": "5"}
]
Array#reduce
按其内部 type
属性的元素对列表进行分组:
const data = [
{"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": "savings", "id": "5"}}
];
const res = data.reduce((acc, curr) => {
if(!acc[curr.account.type]) acc[curr.account.type] = []; //If this type wasn't previously stored
acc[curr.account.type].push(curr);
return acc;
},{});
console.log(res);
现在可以使用最新发布的函数Object.groupBy(array,callbackFun):
const result = Object.groupBy(data, ({type}) => type);
代码更加简洁易读。