Some json data:
[
{
"country": "US",
"id": 1,
"name": "Brad",
},
{
"country": "US",
"id": 2,
"name": "Mark",
},
{
"country": "CAN",
"id": 3,
"name": "Steve",
},
]
What I'd like to do is create a dictionary from this, {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]
What's the best way of going about this with jquery? Dictionaries constantly confound me for some reason.
Some json data:
[
{
"country": "US",
"id": 1,
"name": "Brad",
},
{
"country": "US",
"id": 2,
"name": "Mark",
},
{
"country": "CAN",
"id": 3,
"name": "Steve",
},
]
What I'd like to do is create a dictionary from this, {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]
What's the best way of going about this with jquery? Dictionaries constantly confound me for some reason.
Share Improve this question asked Jan 7, 2014 at 16:14 ChrisChris 571 silver badge5 bronze badges 2-
5
what is
'Brad' 1
? Do you mean['Brad', 1]
?{ name: 'Brad', id: 1 }
?'Brad 1'
? – jbabey Commented Jan 7, 2014 at 16:16 - If that's really what you want...that's awkward. – m59 Commented Jan 7, 2014 at 16:23
2 Answers
Reset to default 3$.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);
});
});
Personally, I don't like converting them to an array, I would keep them as values, which make them easier to manipulate.
var dict = {}
$.each(result, function(i, item){
if(!dict[item.country]) dict[item.country] = [];
dict[item.country].push([item.name, item.id]);
});
You can see this in action on this jsFiddle demo.
For the data you provided, this is the result it gives:
{"US":[["Brad",1],["Mark",2]],"CAN":[["Steve",3]]}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744922037a4601191.html
评论列表(0条)