一些json数据:
[
{
"country": "US",
"id": 1,
"name": "Brad",
},
{
"country": "US",
"id": 2,
"name": "Mark",
},
{
"country": "CAN",
"id": 3,
"name": "Steve",
},
]
我想做的是创建一个字典,{country:[name id]}:
$.getJSON('result.json', function(result) {
var dict = {}
$.each(result, function(key, value){
//build dict
});
});
//{ 'US': ['Brad' 1, 'Mark' 2], 'CAN': ['Steve' 3]
使用jquery进行此操作的最佳方法是什么?由于某些原因,词典经常使我感到困惑.
最佳答案
$.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);
});
});
就个人而言,我不喜欢将它们转换为数组,我会将它们保留为值,这使它们更容易操作.