From my server rest API, I request a javascript object that has the following structure:
[
{
"msgID": 3,
"admTag": {
"tagName": "Employee"
}
},
{
"msgID": 3,
"admTag": {
"tagName": "Safety"
}
},
{
"msgID": 3,
"admTag": {
"tagName": "Performance"
}
},
{
"msgID": 7,
"admTag": {
"tagName": "Role Based Training"
}
},
{
"msgID": 7,
"admTag": {
"tagName": "Account Service Information"
}
},
{
"msgID": 6,
"admTag": {
"tagName": "Consumer Product Safety Improvement"
}
}
]
To use this object on the client, I need to transform the structure to group by the msgID property and assign to it an array containing the values of the associated tagName. Like so:
[{
"3": ["Employee","Safety","Performance"],
"7": ["Role Based Training","Account Service Information"],
"6": ["Consumer Product Safety Improvement"]
}]
I can accomplish this using a nested for loop but I know it can be done more efficiently and with less code using underscore. Using groupBy I am able to get a grouping of the msgID's which gives me the keys I need:
_.groupBy(tags.tags, function(model){
return model.msgID;
});
...but I'm unsure how to 'pluck' the tagNames from the resulting object and assign them to the proper msgID.
Greatly appreciate any help on this!