Reputation: 2461
suppose i have the following json array:
const input = [
{ "tx_type": "215", "dos": "2019-05-02", "payer": "Cigna", "count": 23 },
{ "tx_type": "215", "dos": "2019-05-02", "payer": "SENIORCARE Plus", "count": 75 },
{ "tx_type": "217", "dos": "2019-05-02", "payer": "Aetna", "count": 2 },
{ "tx_type": "215", "dos": "2019-05-03", "payer": "Aetna", "count": 85 },
{ "tx_type": "215", "dos": "2019-05-03", "payer": "TRICARE", "count": 1 },
{ "tx_type": "215", "dos": "2019-05-03", "payer": "Aetna", "count": 5 },
{ "tx_type": "215", "dos": "2019-05-03", "payer": "Cigna", "count": 11 }
]
which comes out of a postgres 9.2 db, but I am trying to fit the data into a dataviz that expects the data to look like:
[
{
"tx_type": "x215",
"dos": [
{ "date": "2019-05-02", "SENIORCARE Plus": 75, "Cigna": 23 },
{ "date": "2019-05-03", "Aetna": 96, "TRICARE": 1, "Cigna": 11 }
],
},
{
"tx_type": "x215",
"dos": [
{ "date": "2019-05-02", "Aetna": 2 }
]
}
]
i have tried using lodash to group the objects by tx_type using .groupBy("tx_type")
, as well as _.chain(input).nest("tx_type").groupBy("dos").value()
, as well as filtering by tx_type and then trying to group/ nest...
really, all I am trying to do is filter by tx_type and group the payers and counts by date.
any input would be greatly appreciated. and as much as i want to upgrading to a newer version of postgres isn't really an option..
Upvotes: 0
Views: 433
Reputation: 191996
Group by tx_type
and map the groups. To create the dos
property, map the items in the group, group them by dos
, map the results to convert each row to an object of { data, [payer]:count }
, and merge the objects:
const input = [{"tx_type":"215","dos":"2019-05-02","payer":"Cigna","count":23},{"tx_type":"215","dos":"2019-05-02","payer":"SENIORCARE Plus","count":75},{"tx_type":"217","dos":"2019-05-02","payer":"Aetna","count":2},{"tx_type":"215","dos":"2019-05-03","payer":"Aetna","count":85},{"tx_type":"215","dos":"2019-05-03","payer":"TRICARE","count":1},{"tx_type":"215","dos":"2019-05-03","payer":"Aetna","count":5},{"tx_type":"215","dos":"2019-05-03","payer":"Cigna","count":11}]
const result = _(input)
.groupBy('tx_type')
.map((dos, tx_type) => ({
tx_type,
dos: _(dos)
.groupBy('dos')
.map((g, date) => _.merge({},
..._.map(g, ({ payer, count }) => ({ date, [payer]: count }))
))
.value()
}))
.value()
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>
Upvotes: 1