2013-02-06 132 views
0

我有一個JSON數組從我的服務器,它看起來像抓取:重新排序JSON集合

 [ {name: "Web Design", id: "27", month_n: "1", data: "68.00"}, 
    {name: "Web Design", id: "27", month_n: "2", data: "56.00"} , 
    {name: "Homework", id: "4", month_n: "2", data: "15.00"} , 
    {name: "Gaming", id: "12", month_n: "2", data: "5.00"} ] 

在客戶端,我要重新排序此有類似的東西:

[{name: "Web Design", data:[68.00,56.00]}, {name:"Homework", data:[0,15]} and so on... 

其中「數據」值按「ID」號碼和月份編號分組(如果沒有匹配的月份,則默認爲0)。

最好的方法是什麼?我嘗試了純粹的JavaScript方式,但我很難過!我也聽說用下劃線JS更容易。但不知道從哪裏開始。

請問有人請賜教嗎?

+3

這是普通的JavaScript,而不是JSON。 – ThiefMaster

+0

_什麼是最好的方法?_因爲它是你的服務器爲什麼不改變服務器腳本的響應? – Andreas

+0

嗯好吧在客戶端上解析後不是JSON。抱歉讓詞彙混淆! – gallab

回答

1

在vanilla JavaScript中執行此操作的一種方法是使用助手對象,如以下代碼所示。

在第一步中,我們確定所有不同的name值並將它們全部組成data字段。 在第二步中,輔助對象被轉換回數組。

var arr = [ {name: "Web Design", id: "27", month_n: "1", data: "68.00"}, 
    {name: "Web Design", id: "27", month_n: "2", data: "56.00"} , 
    {name: "Homework", id: "4", month_n: "2", data: "15.00"} , 
    {name: "Gaming", id: "12", month_n: "2", data: "5.00"} ]; 

// use a helper object to identify all distinct "names" 
var helper = {}; 
for(var i=arr.length; i--;) { 
    // init an array, if it is not there 
    helper[ arr[i]['name'] ] = helper[ arr[i]['name'] ] || []; 

    // add the newest element 
    helper[ arr[i]['name'] ].push(helper[ arr[i]['data'] ]); 
} 

// convert back to an array 
var newArr = []; 
for(var key in helper) { 
if(helper.hasOwnProperty(key)) { 
    newArr.push({ 'name': key, 'data': helper[key] }); 
} 
} 
+0

非常感謝Sirko的幫助,沒想到這麼快就有了答案!我會試試這個! – gallab

1

這可以通過兩個操作來完成:

  1. GROUPBY [名稱]字段,然後
  2. 普呂克[數據]字段

有純JS數組原型擴展庫來實現這一點以及使用幾行代碼實現許多其他操作。你可以看看underscore.js。我也寫了一個簡單的JS庫jsList。它以許多單元測試來作爲例子。

您只需要編寫幾行:

var arr = [ {name: "Web Design", id: "27", month_n: "1", data: "68.00"}, 
      {name: "Web Design", id: "27", month_n: "2", data: "56.00"} , 
      {name: "Homework", id: "4", month_n: "2", data: "15.00"} , 
      {name: "Gaming", id: "12", month_n: "2", data: "5.00"} ]; 

var temp = arr.groupBy(function(item){ return item.name }); 

var result = []; 
for(var key in temp){ 
    result.push({name: key, data: temp[key].pluck('data')}); 
} 

您可以使用Object.keys避免for循環,但只配備使用Javascript 1.8.5或更高版本。

謝謝。