0

Looking to loop through JSON that comes back like this in javascript and access the 'line' and other variables.

{
"2":{"league":"MLB","matchnum":"2","site":"1","line":"-120","teamname":"COL"},
"1":{"league":"MLB","matchnum":"1","site":"2","line":"111","teamname":"SF"}
}

This appears to be the answer but I think the issue is i'm trying to access a value thats in an object in an object.

for(var i = 0; i < json.length; i++) {
    var obj = json[i];

    console.log(obj.id);
}

Where I am going wrong here? Thanks a lot for your time.

1 Answers1

1

There's no id in the JSON provided. If you would like to display 1 and 2, well you can do this way using for ... in loop. Otherwise you can access all the elements from the JavaScript Object this way too.

var json = {
  "2": {
    "league": "MLB",
    "matchnum": "2",
    "site": "1",
    "line": "-120",
    "teamname": "COL"
  },
  "1": {
    "league": "MLB",
    "matchnum": "1",
    "site": "2",
    "line": "111",
    "teamname": "SF"
  }
};
for (var i in json) {
  var obj = json[i];
  console.log(i);
  console.log(obj.teamname);
}

Moreover, the main issue as pointed out by Charlie Martin is that you are trying to call .length on an object, which gives you undesirable results, i.e., the length property of a JavaScript object is not at all defined.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252