Currently tackling an angular project with the goal of converting a list into a specific data structure for compatibility with the TreeSelect component of primeng.
The initial data structure is as follows:
initialDataStructure = [
{ "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "MONTH"},
{ "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "YEAR"},
{ "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "MONTH"},
{ "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "YEAR"},
{ "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod": "MONTH"},
{ "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod": "YEAR"},
{ "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "MONTH"},
{ "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "YEAR",},
]
Attempted a mapping solution provided, but encountered unexpected results. Any alternative methods for achieving the desired map?
for (var i = 0, len = this.listContracts.length, p; i < len; i++) { // faster than .forEach
p = this.listContracts[i];
if (this.grouped[p.country] === undefined) // twice faster then hasOwnProperty
this.grouped[p.country] ={}
if (this.grouped[p.country][p.productType] === undefined)
this.grouped[p.country][p.productType] ={}
if (this.grouped[p.country][p.productType][p.deliveryPeriod] === undefined)
this.grouped[p.country][p.productType][p.deliveryPeriod]=[]
this.grouped[p.country][p.productType][p.deliveryPeriod].push(p); // groupby is HERE xD
}
expectedDataStructure = [
{
label: "GERMANY",
children: [
{
label: "BASE",
children:
[
{
label: "MONTH",
children: [{ "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "MONTH"}]
},
{
label: "YEAR",
children: [{ "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "YEAR"}]
}
]
},
{
label: "PEAK",
children:
[
{
label: "MONTH",
children: [{ "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "MONTH"}]
},
{
label: "YEAR",
children: [{ "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "YEAR"}]
}
]
},
]
},
{
label: "AUSTRIA",
children: [
{
label: "BASE",
children:
[
{
label: "MONTH",
children: [{ "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod": "MONTH"}]
},
{
label: "YEAR",
children: [{ "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod": "YEAR"}]
}
]
},
{
label: "PEAK",
children:
[
{
label: "MONTH",
children: [{ "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "MONTH"}]
},
{
label: "YEAR",
children: [{ "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "YEAR"}]
}
]
},
]
},
]