I'm trying to group the following array with objects base on the siteId:
var Details = [
{
"addressId": "399906",
"extAddressId": null,
"addressType": "ORDER_FULFILLMENT",
"siteId": 101,
"bankAccount": [
{"bankAccountId": "409539","extBankAccountId":null,"primary": true},
{"bankAccountId": "409537","extBankAccountId": null, "primary": false},
{"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
],
"contactId": ["399908"],
"extContactId": null,
"emailForPurchaseOrders": "[email protected]",
"emailForRemittance": "[email protected]",
"emailLanguage": "English"
},
{
"addressId": "399906",
"extAddressId": null,
"addressType": "LEGAL",
"siteId": 101,
"bankAccount": [
{"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
{"bankAccountId": "409540","extBankAccountId":null,"primary": true},
],
"contactId": [],
"extContactId": null,
"emailForPurchaseOrders": "[email protected]",
"emailForRemittance": "[email protected]",
"emailLanguage": "English"
}
]
To something like this:
{
"addressId": ["399906"],
"addressType": ["ORDER_FULFILLMENT", "LEGAL"],
"siteId": 101,
"bankAccount": [
{
"bankAccountId": "409539",
"extBankAccountId": null,
"primary": true
},
{
"bankAccountId": "409537",
"extBankAccountId": null,
"primary": false
},
{
"bankAccountId": "399907",
"extBankAccountId": null,
"primary": false
},
{
"bankAccountId":"409540",
"extBankAccountId":null,
"primary": true
},
],
"contactId": ["399908"],
"emailForPurchaseOrders": ["[email protected]", "[email protected]"],
"emailForRemittance": ["[email protected]","[email protected]"],
"emailLanguage": "English"
},
Right now I'm trying to group it but could not get the above structure to meet my needs. so far this is what i am trying to do to achieve it. Any help be highly appreciated.
var group_to_values = subscriptionDetail.reduce(function (obj, item) {
obj[item.siteId] = obj[item.siteId] || [];
obj[item.siteId].push(item);
return obj;
}, {});
console.log(group_to_values);
var groups = Object.keys(group_to_values).map(function (key) {
return {siteId: key, details: group_to_values[key]};
});
I know I'm missing something but can't figure it out. Any suggestion?