ES6按字段类型分组数组对象 [英] ES6 group array objects by field type
本文介绍了ES6按字段类型分组数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简洁的es6功能性方法可以按类型将项目分组,因为它是不可变的?
Is there a terse es6 functional way to group items by type in that it's immutable?
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"}
]
推荐答案
You can use Array#reduce
to group your list by its elements inner type
property :
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);
这篇关于ES6按字段类型分组数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文