There are multiple items stored in an array:
"objects": [
{
"category": "XXXXX",
"item_name": "over_pkg_0",
"price": 230
},
{
"category": "XXXXX",
"item_name": "over_pkg_1",
"price": 54
},
{
"category": "YYYYY",
"item_name": "over_pkg_0",
"price": 25
},
{
"category": "YYYYY",
"item_name": "over_pkg_1",
"price": 25
}
];
My goal is to reorganize the data using lodash as follows:
"objects": [
{
"XXXXX": [
{
"name": "over_pkg_0",
"amount": 230
},
{
"name": "over_pkg_1",
"amount": 54
}
],
},
{
"YYYYY": [
{
"name": "over_pkg_0",
"amount": 25
},
{
"name": "over_pkg_1",
"amount": 25
}
],
}
];
I have made some attempts, but I can't seem to separate the keys and convert them into arrays. Perhaps utilizing _.concat
could provide a solution, but I haven't been able to implement it successfully.
I tried using:
var revisedObjects = _.chain(objects)
.keyBy('category')
.mapValues(v => _.omit(v, 'category'))
.value();
This code results in:
"revisedObjects": {
"XXXXX": {
"name": "over_pkg_1",
"amount": 54
},
"YYYYY": {
"name": "over_pkg_1",
"amount": 25
}
}