Skip to content

Instantly share code, notes, and snippets.

@wencan
Last active August 29, 2015 14:14
Show Gist options
  • Save wencan/13c991f98989c3178d54 to your computer and use it in GitHub Desktop.
Save wencan/13c991f98989c3178d54 to your computer and use it in GitHub Desktop.
JavaScript二维数组变换:第一维和第二维互换
var src = [
{
"duration": [
0,
"01:10:10"
],
"traffic": [
{
"customer": {
"tags": "!VIP"
},
"sum": 10,
"per": 0.1
},
{
"customer": {
"tags": "!customer"
},
"sum": 20,
"per": 0.2
},
{
"customer": {
"tags": "!staff"
},
"sum": 30,
"per": 0.3
},
{
"customer": {
"tags": null
},
"sum": 40,
"per": 0.4
}
],
"total": 100
},
{
"duration": [
4210,
"03:20:20"
],
"traffic": [
{
"customer": {
"tags": "!VIP"
},
"sum": 100,
"per": 0.1
},
{
"customer": {
"tags": "!customer"
},
"sum": 200,
"per": 0.2
},
{
"customer": {
"tags": "!staff"
},
"sum": 300,
"per": 0.3
},
{
"customer": {
"tags": null
},
"sum": 400,
"per": 0.4
}
],
"total": 1000
}
]
var dst = ['!VIP', '!customer', '!staff', null].map(function(tags){
var value = src.map(function(item){
var traffic = item.traffic.filter(function(traffic){
return traffic.customer.tags === tags;
});
return {
'duration': item.duration,
'sum': traffic.length ? traffic[0].sum : 0
};
})
var total = value.reduce(function(a,b){return a+b.sum}, 0);
value.forEach(function(item){
item.per = Math.round(item.sum*100/total)/100;
})
return {
'customer': {
'tags': tags
},
'traffic': value,
'total': total
}
})
console.dir(dst);
console.log(JSON.stringify(dst));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment