gpt4 book ai didi

javascript - ES6 按字段类型分组数组对象

转载 作者:行者123 更新时间:2023-12-01 15:29:25 25 4
gpt4 key购买 nike

是否有一种简洁的 es6 功能方法可以按类型对项目进行分组,因为它是不可变的?

account.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属性(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);

关于javascript - ES6 按字段类型分组数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49575398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com