javascript - Finding object in nested collection with Underscore.js -


i have collection of teams (in league) so:

var fra1 = {    "sports":[       {          "name":"soccer",          "id":600,          "uid":"s:600",          "leagues":[             {                "name":"french ligue 1",                "abbreviation":"fra.1",                "id":710,                "istournament":false,                "country":{                   "id":7,                   "name":"france",                   "abbreviation":"fra"                },                "uid":"s:600~l:710",                "groupid":9,                "shortname":"ligue 1",                "teams":[                   {                      "id":159,                      "uid":"s:600~t:159",                      "location":"bordeaux",                      "name":"bordeaux",                      "nickname":"bordeaux",                      "abbreviation":"bor",                      "color":"00003e",                   },                   {                      "id":160,                      "uid":"s:600~t:160",                      "location":"paris saint-germain ",                      "name":"paris saint-germain ",                      "nickname":"paris saint-germain ",                      "abbreviation":"psg",                      "color":"000040",                   }                ]             }          ]       }    ], } 

there 20 teams in each var stored in way. then, have 6 such leagues: eng1, esp1, fra1, ger1, ita1, , usa1. put in collection, so:

var = {     "eng1":eng1,     "esp1":esp1,     "fra1":fra1,     "ger1":ger1,     "ita1":ita1,     "usa1":usa1 } 

now, each team (regardless of league they're in) has unique id: in above example, bordeaux has id 159, psg has id 160, , on. want able search all collection unique team teamid, using underscore.js, can't quite syntax down. know search 1 league so:

var obj = _.find(fra1.sports[0].leagues[0].teams, function(obj) { return obj.id == teamid }) 

but can't figure out how across 6 leagues. can help? i'd prefer not have combine collections 1 manually, cumbersome amount of data involved.

edit: i'm using:

for (var league in all) {     var obj = _.find(all[league].sports[0].leagues[0].teams, function(obj) { return obj.id == teamid })      if (obj !== undefined)     {            // things     } } 

but still nicer.

one solution create map of teams team id key , team value:

var teams = {};  _.each(all, function(nation){     _.each(nation.sports[0].leagues[0].teams, function(team){         teams[team.id] = team;     }); }); 

you access team using key:

var psg = teams[160]; 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -