I am using Nodejs & would like to group my object array based on few attributes.
example attr_id
& type
will be unique
const normalizedList =[ {
"attr_id": 1,
"type": "color",
"value_index": 10,
"value_label": "Blue"
},
{
"attr_id": 1,
"type": "color",
"value_index": 15,
"value_label": "Red"
},
{
"attr_id": 2,
"type": "size",
"value_index": 10,
"value_label": "Small"
},
{
"attr_id": 2,
"type": "size",
"value_index": 14,
"value_label": "Big"
}
];
Needs to be converted to
[{
"attr_id": 1,
"type": "color",
"values": [{
"index": 10,
"label": "Blue"
}, {
"index": 15,
"label": "Red"
}
]
}, {
"attr_id": 2,
"type": "size",
"values": [{
"index": 10,
"label": "Small"
}, {
"index": 14,
"label": "Big"
}
]
}
]
I was trying to do this without any packages like "underscore" or "json-aggregate". as not many places in the code we do any grouping/aggregation
Below is how I was able to solve
const groupJson = (arr,g_label) =>{
// group the list by 'attr_id'
const groupedAttrList = normalizedList.reduce((acc, obj)=>{
let key = obj[g_label]
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj)
return acc
},{});
const finalArray = [];
// Now iterate over the groupedAttrList
for (let typeRow in groupedAttrList){
let resultObj = {};
let tempRow = groupedAttrList[typeRow];
// as attr_id,type are unique for the set; picking it from 1st
const {attr_id,type} = tempRow [0];
resultObj .attr_id= attr_id;
resultObj .type= type;
// get all the values
resultObj .values = tempRow .map(v=>{
return {index:v.value_index,label:v.value_label};
});
finalArray.push(resultObj );
}
console.log(finalArray);
};
Test
let tempResult = groupJson(normalizedList,'attr_id');
wanted to learn if there are better ways to do it