在Json中计算数组内的数组

时间:2013-05-28 07:36:39

标签: javascript json

我正在获取此JSON文件。路径数组可以是1到100,

{
"waypoints": [
    {
        "path0": [
            {
                "color": "#0000FF"
            },
            {
                "lat": "37.9875000",
                "lon": "23.7609260"
            },
            {
                "lat": "37.9873130",
                "lon": "23.7607460"
            },
            {
                "lat": "37.9873840",
                "lon": "23.7604100"
            }
        ],
        "path1": [
            {
                "color": "#00FF00"
            },
            {
                "lat": "37.9873840",
                "lon": "23.7604100"
            },
            {
                "lat": "37.9878040",
                "lon": "23.7605670"
            },
            {
                "lat": "37.9882590",
                "lon": "23.7607340"
            }
        ],
        "path2": [
            {
                "color": "#FF0000"
            },
            {
                "lat": "37.9882590",
                "lon": "23.7607340"
            },
            {
                "lat": "37.9884690",
                "lon": "23.7598760"
            }
        ]
    }
]
}

如何在Javascript中查看waypoints内有多少路径(path0,path1,..)数组? 使用obj.waypoints.length返回0。

谢谢。

1 个答案:

答案 0 :(得分:1)

在现代浏览器上,您可以使用Object.keys

var nbpaths = Object.keys(obj.waypoints[0]).length;

为了与ie8兼容,您可以这样算:

var nbpaths = 0;
for (var key in obj.waypoints[0]) nbpaths++;