2014-01-07 24 views
4

一些JSON數據:JQuery的:建立與值的字典作爲數組從Json的

[ 
{ 
"country": "US", 
"id": 1, 
"name": "Brad", 
}, 
{ 
"country": "US", 
"id": 2, 
"name": "Mark", 
}, 
{ 
"country": "CAN", 
"id": 3, 
"name": "Steve", 
}, 
] 

我希望做的是創建這個字典,{國家:[名ID]}:

$.getJSON('result.json', function(result) { 
    var dict = {} 
    $.each(result, function(key, value){ 
     //build dict 
    }); 
}); 

//{ 'US': ['Brad' 1, 'Mark' 2], 'CAN': ['Steve' 3] 

用jquery去解決這個問題的最好方法是什麼?由於某種原因,字典經常讓我感到困惑。

+5

什麼是Brad'1?你的意思是'['布拉德',1]'? '{name:'Brad',id:1}'? ''布拉德1'? – jbabey

+0

如果這真的是你想要的......那很尷尬。 – m59

回答

1
$.getJSON('result.json', function(result) { 
    var dict = {} 
    $.each(result, function(key, value){ 
     //build dict 
     var exists = dict[value.country]; 
     if(!exists){ 
     dict[value.country] = []; 
     } 
     exists.push([value.name, value.id]); 
     //if it was my code i would do this ... 
     //exists.push(value); 
    }); 
}); 

就個人而言,我不喜歡把它們轉換成一個數組,我將讓他們作爲值,這使得它們更容易操縱。

+0

謝謝你的幫助。 – Chris

1
var dict = {} 
$.each(result, function(i, item){ 
    if(!dict[item.country]) dict[item.country] = []; 
    dict[item.country].push([item.name, item.id]); 
}); 

您可以在此jsFiddle demo上看到此操作。

對於您所提供的數據,這是它給出結果:

{"US":[["Brad",1],["Mark",2]],"CAN":[["Steve",3]]} 
相關問題