2013-02-20 77 views
1

JSON文件如何計算不同的值以JSON

{"people":[{"Name":"Ray Parker","Email":"[email protected]","State":"Wyoming","Country":"Tuvalu","Martial Status":"Divorced","Department Name":"Tech Support","Company Name":"Borland","Title":"Dr.","Gender":"Male"}, 
{"Name":"Davis Hooper","Email":"[email protected]","State":"Nunavut","Country":"Bangladesh","Martial Status":"Divorced","Department Name":"Public Relations","Company Name":"Cakewalk","Title":"Mr.","Gender":"Female"}, ...... and so on 

我喜歡做一個JSON對象從這個與國家的不同的價值觀和人在該國的計數。

我試過代碼

 $(document).ready(function() { 

    var data = $.ajax({ 
     url: "Data_prop.json", 
     dataType: "json", 
     async: false 
    }).responseText; 

    var unique = {}; 
    var param = "Country" 
    $.each(data.people, function() { 
     if (!unique[this[param]]) 
      unique[this[param]] = []; 
     unique[this[param]].push(this); 
    }); 

    for(var d in unique) { 
     alert(d); 
    } 

     }); 

我在控制檯得到了錯誤

TypeError: a is undefined 
https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js 
Line 2 

哪位有一個想法如何做到這一點?

+0

我不認爲你可以'推()'到對象的值。它的用途是在數組上使用。 – Johan 2013-02-20 09:27:22

+0

有錯誤在你的jQuery庫包括由你。請將圖書館更換爲其他圖書館。 – 2013-02-20 09:27:38

+0

@GauravVashishtha我使用CDN Okky 2013-02-20 09:32:35

回答

1

嘗試

function(data) 
{ 
    var variables = {}; 
    var param = "Country" 
    $.each(data.people, function() 
    { 
     if (!variables[this[param]]) 
      variables[this[param]] = [];  
     variables[this[param]].push(this); 
    }); 

    for(var d in variables) { 
     // add d to array here 
     // or do something with d 
     // variables[d] is the array of people 
    } 
} 
+0

感謝名單,現在它的工作:) – Okky 2013-02-20 09:40:57