循环元素json数组

时间:2015-09-28 17:36:01

标签: javascript jquery json

在本地存储中,我有这种语法

关键

#setupHospitalCity:hospitalCity  

{"data":
[
    {"cityId":1,"city":"Abercorn"},
    {"cityId":2,"city":"ActonVale"},
    {"cityId":3,"city":"Adstock"},
    {"cityId":4,"city":"Aguanish"},
    {"cityId":5,"city":"Akulivik"}
],
"ttl":1443541460054}

使用此代码,

var values = localStorage.getItem("#setupHospitalCity:hospitalCity");   

我得到所有的值

如何仅循环到这些块

{"cityId":1,"city":"Abercorn"},
{"cityId":2,"city":"ActonVale"},
{"cityId":3,"city":"Adstock"},
{"cityId":4,"city":"Aguanish"},
{"cityId":5,"city":"Akulivik"}

3 个答案:

答案 0 :(得分:1)

var data = {"data":
            [
                {"cityId":1,"city":"Abercorn"},
                {"cityId":2,"city":"ActonVale"},
                {"cityId":3,"city":"Adstock"},
                {"cityId":4,"city":"Aguanish"},
                {"cityId":5,"city":"Akulivik"}
            ],
            "ttl": 1443541460054
        }

        for (var x = 0; x < data["data"].length; x++) {
            alert(data["data"][x].city)
        }

答案 1 :(得分:1)

getAction

答案 2 :(得分:1)

你可以像任何其他数组一样循环它:

var values = localStorage.getItem("#setupHospitalCity:hospitalCity");   

var data = values.data;
for (var i = 0, len = values.data; i < len; i++) {
    console.log(values.data[i]); //values.data[i].cityId ...
}