Lodash:使用Lodash对json对象进行分组和重组
问题描述:
如何使用lodash对json对象进行分组和重组。 有这样Lodash:使用Lodash对json对象进行分组和重组
var data = [
{
"Type": "W",
"Id": 1,
"Employee_Role_Desc": null,
"Employee_Role_Id": 1,
"StartDateTime": "2017-06-15T09:00:00",
"EndDateTime": "2017-06-15T12:30:00",
"Alert": null
},
{
"Type": "W",
"Id": 1,
"Employee_Role_Desc": null,
"Employee_Role_Id": 1,
"StartDateTime": "2017-06-15T09:00:00",
"EndDateTime": "2017-06-15T12:30:00",
"Alert": null
}, {
"Type": "W",
"Id": 1,
"Employee_Role_Desc": null,
"Employee_Role_Id": 3,
"StartDateTime": "2017-06-15T09:00:00",
"EndDateTime": "2017-06-15T12:30:00",
"Alert": null
}
]
JSON对象要像这组吨。
{
"Role_Id": 1,
"Date": "2017-06-15T05:12:22.9577063-05:00",
"**Blocks**": [
{
"StartDateTime": "2017-06-15T05:12:22.9586499-05:00",
"EndDateTime": "2017-06-15T05:12:22.9586499-05:00"
},
{
"StartDateTime": "2017-06-15T05:12:22.9586499-05:00",
"EndDateTime": "2017-06-15T05:12:22.9586499-05:00"
}
]
}
集团它由Employee_Role_Id并且每个的startDateTime和EndDateTime应在结果的块对象 “ROLE_ID”应是“Employee_Role_Id”中得到的对象。
答
可以实现在一个链使用_.groupBy()
和_.map()
:
const data = [{"Type":"W","Id":1,"Employee_Role_Desc":null,"Employee_Role_Id":1,"StartDateTime":"2017-06-15T09:00:00","EndDateTime":"2017-06-15T12:30:00","Alert":null},{"Type":"W","Id":1,"Employee_Role_Desc":null,"Employee_Role_Id":1,"StartDateTime":"2017-06-15T09:00:00","EndDateTime":"2017-06-15T12:30:00","Alert":null},{"Type":"W","Id":1,"Employee_Role_Desc":null,"Employee_Role_Id":3,"StartDateTime":"2017-06-15T09:00:00","EndDateTime":"2017-06-15T12:30:00","Alert":null}];
const result = _(data)
.groupBy('Employee_Role_Id') // group the items
.map((group, Role_Id) => ({ // map the groups to new objects
Role_Id,
Date: group[0].StartDateTime,
Blocks: group.map(({ StartDateTime, EndDateTime }) => ({ // extract the dates from the groups
StartDateTime,
EndDateTime
}))
}))
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
应该用' “Employee_Role_Id” 的项目:3'被忽略? – RomanPerekhrest
@RomanPerekhrest No.还需要 – Aswathy
纯JS解决方案如何? – RomanPerekhrest