如何遍历深层嵌套的json对象

时间:2015-08-23 15:35:55

标签: javascript json for-loop

     var City ={
"City1": [{"name": "Place 1"},{"name": "Place 2"},{"name": "Place 3"}],
"City2":[{"name":"My Place 1"},{"name":"My Place 2"},{"name":"My Place 3"}],
"City3":[{"name":"My Place 1"},{"name":"My Place 2"},{"name":"My Place 3"}]
    };

我想使用JavaScript循环获取第一个城市名称,然后循环获取其位置,然后获取第二个城市及其位置等等。

3 个答案:

答案 0 :(得分:4)

您可以使用for循环遍历City对象的所有属性:

for (var key in City) {
    if (City.hasOwnProperty(key)) {
        var values = City[key];
        // "key" will be City1, City2, ...
        // "values" will be the corresponding array through which
        // you can loop
    }
}

答案 1 :(得分:2)

尝试使用Object.keys()Array.prototype.forEach()

var City = {
  "City1": [{
    "name": "Place 1"
  }, {
    "name": "Place 2"
  }, {
    "name": "Place 3"
  }],
  "City2": [{
    "name": "My Place 1"
  }, {
    "name": "My Place 2"
  }, {
    "name": "My Place 3"
  }],
  "City3": [{
    "name": "My Place 1"
  }, {
    "name": "My Place 2"
  }, {
    "name": "My Place 3"
  }]
};

Object.keys(City).forEach(function(value, key) {
  console.log(value);
  City[value].forEach(function(v, k) {
    console.log(v.name)
  })
});

答案 2 :(得分:0)

for (let key in City) {
    let value = City[key];
    console.log(key);
    for (i = 0; i <= value.length; i++) {
      console.log(value[i]);
    }
  }