ES6 按字段类型对数组对象进行分组

问题描述 投票:0回答:2

是否有一种简洁的 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"}
]
javascript collections ecmascript-6
2个回答
33
投票

您可以使用

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);


0
投票

现在可以使用最新发布的函数Object.groupBy(array,callbackFun):

const result = Object.groupBy(data, ({type}) => type);

代码更加简洁易读。

© www.soinside.com 2019 - 2024. All rights reserved.