2016-09-10 122 views
1

我有一個對象來自服務器通過JSON格式如下。我想重新排列它爲另一種格式。在JavaScript中更改JSON結構/ Jquery

{ 
    visits: [{ 
     week: 1, 
     count: 3 
    }, { 
     week: 2, 
     count: 3 
    }, { 
     week: 3, 
     count: 4 
    }, { 
     week: 4, 
     count: 3 
    }, { 
     week: 5, 
     count: 1 
    }], 
    visitors: [{ 
     week: 1, 
     count: 3 
    }, { 
     week: 2, 
     count: 3 
    }, { 
     week: 3, 
     count: 4 
    }, { 
     week: 4, 
     count: 3 
    }, { 
     week: 5, 
     count: 1 
    }] 
} 

我想改變其結構,並希望下面這個格式:

{ 
    week1: { 
     visits: 3 
     visitors: 1 
    } 
    week2: { 
     visits: 3 
     visitors: 3 
    } 
    week3: { 
     visits: 4 
     visitors: 4 
    } 
    week4: { 
     visits: 3 
     visitors: 3 
    } 
    week5: { 
     visits: 4 
     visitors: 4 
    } 
} 
+0

什麼都*** ***你試過嗎?任何代碼分享? –

+0

這不是JSON,並且即使您將數據作爲JSON獲取,也與問題無關。 –

回答

0

所以使用GROUPBY功能:

var groupBy=function(jsonArray,key) { 
     return jsonArray.reduce(function(rv, x) { 
     (rv[x[key]] = rv[x[key]] || []).push(x); 
     return rv; 
     }, {}); 
    }; 

然後:

var groupedByWeeks=groupBy(yourJsonArray.visits,'week') 

然後映射對象1->week1,.. n->weekn

Object.keys(groupedByWeeks).map((k)=> 
    groupedByWeeks['week'+k]=groupedByWeeks[k]; 
) 
1

試試這個:

var newObj = {} 

$.each(a.visits, function(key,obj){ newObj['week'+obj.week] ={visits: obj.count} }); 

$.each(a.visitors, function(key,obj){ newObj['week'+obj.week].visitors = obj.count});