我如何在JavaScript中表示以下菜单结构?

时间:2012-03-07 11:35:47

标签: javascript

Soccer
  Australia
    Melbourne
    Sydney
  New Zealand
    Christchurch
Tennis
  United Kingdom
    Kensington
    London
    Manchester

我尝试了多维数组,但由于长度不同,它变得很笨拙。我也尝试过键/值对但是我再次遇到了困难,因为在某种程度上只有值而没有键。我试图直观地表示层次结构。澄清悉尼是澳大利亚的孩子。澳大利亚是足球的孩子。足球是网球的兄弟等等。

编辑:我正在寻找一种不需要任何实际数据知识的解决方案。换句话说,我可以用“棒球”替换“足球”,并且只打印出数据结构的简单算法不应该破坏。

2 个答案:

答案 0 :(得分:4)

在JSON中:

{
    "Soccer": {
        "Australia": [
            "Melbourne",
            "Sydney"
        ],
        "NewZealand": [
            "Christchurch"
        ]
    },
    "Tennis": {
        "UnitedKingdom": [
            "Kensington",
            "London",
            "Manchester"
        ]
    }
}

以下是数据循环:

for ( sport in data ) {
    // print sport here
    countries =  data[sport];    
    for ( country in countries ) {
        // print country here
        cities = countries[country];
        for (var i = 0; i < cities.length; i++) {
            // print city here
        };
    };
};​

可以在jsFiddle上看到:http://jsfiddle.net/2p6g3/18/

答案 1 :(得分:0)

{
"sport": [
    {
        "name": "Soccer",
        "place": [
            {
                "country": "Australia",
                "city": [
                    {
                        "name": "Melbourne"
                    },
                    {
                        "nam": "Sdney"
                    }
                ]
            },
            {
                "country": "NewZealand",
                "city": [
                    {
                        "name": "Christchurch"
                    }
                ]
            }
        ]
    },
    {
        "name": "Tennis",
        "place": [
            {
                "country": "UnitedKingdom",
                "city": [
                    {
                        "name": "Manchester"
                    }
                ]
            }
        ]
    }
]

}

遍历对象数组以获取必填字段:

sport[].name // name of the sports
sport[].place[].country // country name
sport[].place[].city[].name // city name