javascript - JQuery: Building a dictionary with values as an array from Json - Stack Overflow

Some json data:[{"country": "US","id": 1,"name": "Brad

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
Add a ment  | 

2 Answers 2

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信