访问嵌套的json数组对象并确定数组长度

时间:2016-07-24 10:39:12

标签: javascript arrays json nested

这是我的json文件,我正在尝试访问组内的属性,例如homeTeam和markerImage。

如何确定比赛内的小组数量。请帮忙!

{
   "competition":{
      "group1":[
         {
            "homeTeam":"Lawrence Library",
            "markerImage":"images/red.png",
         },
         {
            "homeTeam":"Hamilton Library",
            "markerImage":"images/white.png",

         },
         {
            "homeTeam":"Applebees",
            "markerImage":"images/newcastle.png",

         }
      ],
      "group2":[
         {
            "homeTeam":"Lawrence Library",
            "markerImage":"images/red.png",

         },
         {
            "homeTeam":"Hamilton Library",
            "markerImage":"images/white.png",

         },
         {
            "homeTeam":"Applebees",
            "markerImage":"images/newcastle.png",
         }
      ]
   }
}

2 个答案:

答案 0 :(得分:1)

要确定竞赛对象中的组数,您可以使用

Object.keys(obj.competition).length

console.log(Object.keys(obj.competition).length);

让你的小组循环尝试这样的事情

for(var x in Object(obj.competition.group1)){
    var newObj = Object(obj.competition.group1[x]);
    console.log(newObj.homeTeam + ' and '+ newObj.markerImage);
}

答案 1 :(得分:0)

  1. 解析您的JSON对象并将其存储在javascript对象中
  2. 使用下划线和lo-Dash库计算对象数
  3. Link to calculate it with Underscore and Lo-Dash libraries