-1

I'm having a very simple JSON file which looks like:

{
 "seasons" : {
    "s_1" : {
        "episodes" : 7
    },
    "s_2" : {
        "episodes" : 21
    },
    "s_3" : {
        "episodes" : 22
    },
    "s_4" : {
        "episodes" : 30
    },
    "s_5" : {
        "episodes" : 18
    },
    "s_6" : {
        "episodes" : 12
    }
  }
}

and I want to randomly select a s_ x value from seasons when parsing the file:

var random = Math.floor(Math.random() * 6) + 1;
    $.getJSON('js/data.json', function(data) {         
        console.log(data.seasons.s_+random);
    });

this obviously does not work. How would be the correct way? Thanks

supersize
  • 13,764
  • 18
  • 74
  • 133

1 Answers1

1

Does this work?

console.log(data.seasons["s_"+random]);

Using brackets so it becomes something like data.seasons["s_1"]

MingShun
  • 287
  • 3
  • 11
  • it does! I'm just wondering why you can miss the point there. – supersize Mar 20 '15 at 21:38
  • 2
    @supersize: Simply because that's how the syntax is defined. A property can either be accessed using dot (`foo.bar`) or bracket notation (`foo['bar']`). – Felix Kling Mar 20 '15 at 21:40
  • Because the way it's listed would induce a different kind of error. data.seasons.s_+random would give an undefined error wouldn't it? When you look for data.seasons.s_ (undefined) and try to concatenate/add random to it. – MingShun Mar 20 '15 at 21:41
  • @MingShun: It would not throw an error. The result would be `NaN` (e.g. `undefined + 1`). – Felix Kling Mar 20 '15 at 21:44
  • Why not just attach a "length" property on the same level as s_1, s_2, s_3 to the json file? Then generate the random number with it. – MingShun Mar 20 '15 at 21:44
  • @Felix Kling: Thanks! I'm getting confused with all of the errors that can pop up between PHP, Javascript, and MySQL. I'll try and remember this. – MingShun Mar 20 '15 at 21:50