我是 underscore js 库的新手,我正在尝试重新组织我的一些数据,以便更好地满足我的应用程序需求。我的 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",
}
]
}
我想映射数据,以便我可以提取唯一behaviour
名称,并创建一个具有behaviours
分组的新数组。所以我的数据看起来像这样:
{
"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"
}
]
}
]
}
我目前有以下代码,它没有做很多事情,我被这个问题困住了,我不确定如何有效地解决它。
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': []
};
});
};
我不确定如何push
将事件对象 {event_id
和event_number
} 放入事件数组中,同时name
将behavior
对象的 与新数组的behavior
对象匹配。任何帮助表示赞赏。