gpt4 book ai didi

javascript - 如何按子值将对象数组拆分为多个对象数组

转载 作者:行者123 更新时间:2023-11-28 15:10:44 25 4
gpt4 key购买 nike

我需要按其对象子值(类型)拆分数组。假设我有以下数组:

[
{id:1,name:"John",information: { type :"employee"}},
{id:2,name:"Charles",information: { type :"employee"}},
{id:3,name:"Emma",information: { type :"ceo"}},
{id:4,name:"Jane",information: { type :"customer"}}
]

我想按信息类型分割对象,所以我的最终结果如下:

[
{
type:"employee",
persons:
[
{id:1,name:"John",information: { ... }},
{id:2,name:"Charles",information: { ... }
]
},
{
type:"ceo",
persons:
[
{id:3,name:"Emma",information: { ... }}
]
},
{
type:"customer",
persons:
[
{id:4,name:"Jane",information: { ... }}
]
},
]

下划线在我的项目中可用。可以包含任何其他帮助程序库。

当然,我可以循环遍历数组并实现我自己的逻辑,但我一直在寻找更干净的解决方案。

最佳答案

这将返回您想要的内容:

_.pairs(_.groupBy(originalArray, v => v.information.type)).map(p => ({type: p[0], persons: p[1]}))

关于javascript - 如何按子值将对象数组拆分为多个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36578509/

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