【问题标题】:Access nested json array object and determine array length访问嵌套的 json 数组对象并确定数组长度
【发布时间】:2016-07-24 10:39:12
【问题描述】:

这是我的 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",
         }
      ]
   }
}

【问题讨论】:

    标签: javascript arrays json nested


    【解决方案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);
    }
    

    【讨论】:

      【解决方案2】:
      1. 解析您的 JSON 对象并将其存储在 javascript 对象中
      2. 使用下划线和 lo-Dash 库计算对象数量

      Link to calculate it with Underscore and Lo-Dash libraries

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 2015-08-13
        • 2017-11-27
        • 2015-10-25
        相关资源
        最近更新 更多