Javascript 如何遍历 json 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13544551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:19:29  来源:igfitidea点击:

How to iterate through a json object?

javascriptjquery

提问by Guffa

Possible Duplicate:
I have a nested data structure / JSON, how can access a specific value?

可能重复:
我有一个嵌套的数据结构/JSON,如何访问特定值?

I want to iterate through a json object which is two dimensional ... for a one dimensional json object I do this

我想遍历一个二维的 json 对象......对于一个一维的 json 对象,我这样做

for (key in data) {
alert(data[key]);
}

what do i do about a two dimensional one??

我该怎么办一个二维的??

回答by Guffa

There is no two dimensional data in Javascript, so what you have is nested objects, or a jagged array (array of arrays), or a combination (object with array properties, or array of objects). Just loop through the sub-items:

Javascript 中没有二维数据,因此您拥有的是嵌套对象,或锯齿状数组(数组数组),或组合(具有数组属性的对象,或对象数组)。只需循环遍历子项:

for (var key in data) {
  var item = data[key];
  for (var key2 in item) {
    alert(item[key2]);
  }
}

回答by John Dvorak

perhaps you want

也许你想要

for(var i in data){
  for(var j in data[i]){
    alert(data[i][j]);
  }
}

回答by IProblemFactory

Try:

尝试:

for (var key in data) {
   for (var key2 in data[key]){
      alert(data[key][key2]);
   }
}