作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要按其对象子值(类型)拆分数组。假设我有以下数组:
[
{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/
我是一名优秀的程序员,十分优秀!