Chris
Chris

Reputation: 57

JQuery: Building a dictionary with values as an array from Json

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.

Upvotes: 4

Views: 6549

Answers (2)

Peter Olson
Peter Olson

Reputation: 143037

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]]}

Upvotes: 1

Nix
Nix

Reputation: 58622

$.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.

Upvotes: 3

Related Questions