JQuery: Building a dictionary with values as an array from Json
javascript, jquery, json
Solution
$.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.
Problem
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.