How can I take an array of objects like this:
let data = [
{
"FirstName": "TRACY",
"Code": "CCI41",
"UtilName": "Cable",
"gridid": 570
},
{
"FirstName": "ANGELA",
"Code": "TWCZ40",
"UtilName": "Cable",
"gridid": 570
},
{
"FirstName": "WILFORD",
"Code": "TCE12",
"UtilName": "Electric",
"gridid": 570
},
{
"FirstName": "COREY",
"Code": "SCEJZ40",
"UtilName": "Electric",
"gridid": 570
},
{
"FirstName": "ERNEST",
"Code": "SGRAZ01",
"UtilName": "Fiber",
"gridid": 570
},
{
"FirstName": "WILFORD",
"Code": "TCE12",
"UtilName": "Fiber",
"gridid": 570
},
{
"FirstName": "COREY",
"Code": "SCGZ02",
"UtilName": "Gas",
"gridid": 570
},
{
"FirstName": "ANGELO",
"Code": "BSZT29",
"UtilName": "Phone",
"gridid": 570
}
]
And turn it to an array like this that contains grouped per gridid per UtilName:
let newArr = [
{
570: [
{
"Cable": [
{
"FirstName": "Tracey",
"Code": "CCI41"
}, {
"FirstName": "ANGELA",
"Code": "TWCZ40"
}
],
"Electric": [
{
"FirstName": "WILFORD",
"Code": "TCE12"
}, {
"FirstName": "COREY",
"Code": "SCEJZ40"
}
],
"Fiber": [
{
"FirstName": "WILFORD",
"Code": "TCE12"
}
],
"Gas": [
{
"FirstName": "COREY",
"Code": "SCGZ02"
}
],
"Phone": [
{
"FirstName": "ANGELO",
"Code": "BSZT29"
}
]
}
]
}
]
It can be structured in alternative ways but the goal is to get each person grouped into a gridid and UtilName.
>Solution :
let data = [
{"FirstName": "TRACY","Code": "CCI41","UtilName": "Cable","gridid": 570},
{"FirstName": "ANGELA","Code": "TWCZ40","UtilName": "Cable","gridid": 570},
{"FirstName": "WILFORD","Code": "TCE12","UtilName": "Electric","gridid": 570},
{"FirstName": "COREY","Code": "SCEJZ40aa","UtilName": "Electric","gridid": 570},
{"FirstName": "COREY","Code": "SCEJZ40","UtilName": "Electric","gridid": 580},
{"FirstName": "COREY","Code": "SCEJZ40a","UtilName": "Electric","gridid": 580}
];
let expected_output = {}
data.forEach(elem => {
if(!(elem['gridid'] in expected_output)){
expected_output[elem['gridid']] = [{}]
}
if(!(elem['UtilName'] in expected_output[elem['gridid']][0])){
expected_output[elem['gridid']][0][elem['UtilName']] = []
}
const j = expected_output[elem['gridid']][0][elem['UtilName']].length
expected_output[elem['gridid']][0][elem['UtilName']][j] = {'FirstName' : elem['UtilName'],'Code' : elem['Code']}
});
console.log(expected_output)