Reputation: 2834
How can i group and restructure the json object using lodash. Have a json object like this
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
}
]
Want to group t like this.
{
"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"
}
]
}
Group it by Employee_Role_Id and each StartDateTime and EndDateTime should be in a Blocks object "Role_Id" in the result should be the "Employee_Role_Id" in resultant object.
Upvotes: 1
Views: 1270
Reputation: 192016
You can achieve that using _.groupBy()
, and _.map()
in a chain:
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>
Upvotes: 1