我有一个来自数据库的对象数组,我想要折叠以获得简洁。我已经导入了underscore.js以帮助完成此过程,并且尝试使用' groupBy'提供的功能是为了压缩以下列表:
[
{ID:2570,name:"jim",latitude:59.4,longitude:-7.29},
{ID:2573,name:"joe",latitude:54.4,longitude:-7.36},
{ID:2573,name:"joe",latitude:54.3,longitude:-7.37},
{ID:2574,name:"bob",latitude:58.4,longitude:-7.31},
{ID:2574,name:"bob",latitude:58.6,longitude:-7.38},
{ID:2574,name:"bob",latitude:58.8,longitude:-7.39},
{ID:2575,name:"mary",latitude:54.1,longitude:-7.30},
]
格式:
[
{ID:2570, name:"jim", locs : [[59.4,-7.29]]},
{ID:2573, name:"joe", locs : [[54.4,-7.36], [54.3,-7.37]]} //etc...
]
答案 0 :(得分:2)
遵循您的直觉使用_.groupBy
,
var data = [
{ID:2570,name:"jim",latitude:59.4,longitude:-7.29},
{ID:2573,name:"joe",latitude:54.4,longitude:-7.36},
{ID:2573,name:"joe",latitude:54.3,longitude:-7.37},
{ID:2574,name:"bob",latitude:58.4,longitude:-7.31},
{ID:2574,name:"bob",latitude:58.6,longitude:-7.38},
{ID:2574,name:"bob",latitude:58.8,longitude:-7.39},
{ID:2575,name:"mary",latitude:54.1,longitude:-7.30},
];
var groups = _.groupBy(data, function(locationObject) { return locationObject.ID; });
var result = _.map(groups, function(group) {
var condensed = {ID: group[0].ID, name: group[0].name};
condensed.locs = _.map(group, function(row) {
return [row.latitude, row.longitude];
});
return condensed;
});
document.getElementById('log').innerHTML = JSON.stringify(result, null, ' ');

<script src="http://underscorejs.org/underscore-min.js"></script>
<pre id="log"></pre>
&#13;
答案 1 :(得分:0)
我认为您可以这样使用_.reduce
方法:
_.reduce(data, function(prev, curr) {
var obj = _.findWhere(prev, {ID: curr.ID});
if (obj) {
obj.locs.push([curr.latitude, curr.longitude]);
}
else {
curr.locs = [[curr.latitude, curr.longitude]];
prev.push(_.omit(curr, ['latitude', 'longitude']));
}
return prev;
}, []);
答案 2 :(得分:0)
var
input = [
{ID:2570,name:"jim",latitude:59.4,longitude:-7.29},
{ID:2573,name:"joe",latitude:54.4,longitude:-7.36},
{ID:2573,name:"joe",latitude:54.3,longitude:-7.37},
{ID:2574,name:"bob",latitude:58.4,longitude:-7.31},
{ID:2574,name:"bob",latitude:58.6,longitude:-7.38},
{ID:2574,name:"bob",latitude:58.8,longitude:-7.39},
{ID:2575,name:"mary",latitude:54.1,longitude:-7.30},
]
, output = {} //Handles filtering
, outputArray = [] //Not mandatory, if you want output to be an array
;
for(var key,i=-1;++i<input.length;){
key = input[i].ID; //if ID is unique and ID/name combination is always same
//key = input[i].ID + input[i].name; //if not
if(!output[key]){
output[key] = {ID : input[i].ID, name : input[i].name, locs : []};
outputArray.push(output[key]);
}
output[key].locs.push([input[i].latitude, input[i].longitude]);
}
console.dir(output);
console.dir(outputArray);