I am trying to get an object from another javascript object. I have written the following code to group:
function execute(args) {
const networkHospitals = args[0];
cummulatedArray = _.groupBy(networkHospitals, "cityName");
console.log(cummulatedArray);
}
Here's the sample output that I get from the above code:
{
Trichy: [
{
hospitalName: 'asd',
address_1: 'Friday',
}
]
}
But I want to return the data in this format:
{
"key": "Tirchy",
"value": [{
"hospitalName": "asd",
"address_1": "Friday"
}],
}
Here's the input data:
"networkHospitals":
[{
"hospitalName": "abc",
"address_1": "Friday",
"cityName": "Trichy"
}],
I would be really grateful, if you can guide me how to manipulate this JSON data that I am getting.
After grouping by cityName
, map the groups, and create an object for each group. If needed map the values, and omit the cityName
property from each object.
const networkHospitals = [{"hospitalName":"abc","address_1":"Friday","cityName":"Trichy"}]
const result = _.map(
_.groupBy(networkHospitals, 'cityName'),
(val, key) => ({
key,
value: val.map(o => _.omit(o, 'cityName'))
})
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>