I'm new to the underscore js library and I am trying to reorganize some of my data so that it suits my application needs better. I have the following data coming in from my API:
{
"id": "123456",
"first_name": "John",
"last_name": "Doe",
"behaviours": [
{
"id": 17,
"name": "Following Too Closely",
"event_id": "01234-01234-01234",
"event_number": "ABG4482",
},
{
"id": 19,
"name": "Not Looking Far Ahead",
"event_id": "01234-01234-01234",
"event_number": "ABG4482",
},
{
"id": 19,
"name": "Not Looking Far Ahead",
"event_id": "01234-01234-01234",
"event_number": "ABG4481",
}
]
},
{
"id": "123456",
"first_name": "Jane",
"last_name": "Doe",
"behaviours": [
{
"id": 17,
"name": "Following Too Closely",
"event_id": "01234-01234-01234",
"event_number": "ABG4482",
},
{
"id": 19,
"name": "Not Looking Far Ahead",
"event_id": "01234-01234-01234",
"event_number": "ABG4482",
},
{
"id": 19,
"name": "Not Looking Far Ahead",
"event_id": "01234-01234-01234",
"event_number": "ABG4481",
}
]
}
I want to map the data so that I can pluck out the unique behaviour names, and create a new array that has the behaviours grouped. So my data would look like this:
{
"id": "123456",
"first_name": "John",
"last_name": "Doe",
"behaviours": [
{
"id": 17
"name": "Following Too Closely",
"events": [
{
"event_id": "01234-01234-01234",
"event_number": "ABG4482"
}
]
},
{
"id": 19,
"name": "Not Looking Far Ahead",
"events": [
{
"event_id": "01234-01234-01234",
"event_number": "ABG4482"
},
{
"event_id": "01234-01234-01234",
"event_number": "ABG4481"
}
]
}
]
},
{
"id": "123456",
"first_name": "Jane",
"last_name": "Doe",
"behaviours": [
{
"id": 17
"name": "Following Too Closely",
"events": [
{
"event_id": "01234-01234-01234",
"event_number": "ABG4482"
}
]
},
{
"id": 19,
"name": "Not Looking Far Ahead",
"events": [
{
"event_id": "01234-01234-01234",
"event_number": "ABG4482"
},
{
"event_id": "01234-01234-01234",
"event_number": "ABG4481"
}
]
}
]
}
I've currently got the following code which isn't doing a whole lot, I am stuck on this problem and I'm not sure how to go about it efficiently.
for (var i = $scope.eventData.drivers.length - 1; i >= 0; i--) {
// Create an array containing only the unique behavior names
var behaviourArray = _.uniq(_.pluck($scope.eventData.drivers[i].behaviours, 'name'));
// Create a property containing a joined array of the behavior names
$scope.eventData.drivers[i].behaviourNames = behaviourArray.join(', ');
behaviourArray = _.map(behaviourArray, function(name) {
return {
'name': name,
'events': []
};
});
};
I'm not sure how to push the event objects {event_id, and event_number} into the events array while matching the name of the behavior object with the new array's behavior object. Any help is appreciated.