遍历嵌套的Object Literal数据

时间:2017-02-17 20:35:25

标签: javascript multidimensional-array nested traversal object-literal

一直在浏览论坛,除非我做错了,否则我见过的所有解决方案都没有为我的案例工作过。我试图列出连接到jQuery地图插件的不同状态的数据。基本上,用户将点击一个州,州法律将附加在地图下方。现在我的JSON树看起来像:

var states = {
   "AL" : {
       "longname" : "Alabama",
       "lawOne" : "Text for Law 1",
       "lawTwo" : "Text for Law 2",
       "lawThree" : "Text for Law 3"
   },
   "AK" : {
       "longname" : "Alaska",
       "lawOne" : "Text for Law 1",
       "lawTwo" : "Text for Law 2",
       "lawThree" : "Text for Law 3"
   },
   etc...
}

使用问题here的答案,我可以深入到第2层嵌套数据,但状态的入口点似乎是阻碍。我需要缩写的州名,因为这是地图API在点击状态时吐出的数据。知道为了使这项工作可能需要实施哪些其他步骤?似乎没有找到对象内的对象的答案。提前谢谢!

编辑:一旦我意识到自己很笨拙并且这是一个Object Literal而不是JSON,我找到了我正在寻找的确切答案。我找到了答案here

2 个答案:

答案 0 :(得分:2)

您只需使用Object.keys()获取缩写名称,该名称定义为state对象的属性。



var states = {
   "AL" : {
       "longname" : "Alabama",
       "lawOne" : "Text for Law 1",
       "lawTwo" : "Text for Law 2",
       "lawThree" : "Text for Law 3"
   },
   "AK" : {
       "longname" : "Alaska",
       "lawOne" : "Text for Law 1",
       "lawTwo" : "Text for Law 2",
       "lawThree" : "Text for Law 3"
   }
}

console.log(Object.keys(states))




答案 1 :(得分:2)

你可以迭代并获得这样的短名称:

var states = {
   "AL" : {
       "longname" : "Alabama",
       "lawOne" : "Text for Law 1",
       "lawTwo" : "Text for Law 2",
       "lawThree" : "Text for Law 3"
   },
   "AK" : {
       "longname" : "Alaska",
       "lawOne" : "Text for Law 1",
       "lawTwo" : "Text for Law 2",
       "lawThree" : "Text for Law 3"
   }
}

for (var key in states) {
  if (states.hasOwnProperty(key)) {
    var val = states[key];
    console.log(key + ':' + val.longname);
  }
}

JSFiddle:https://jsfiddle.net/12bor11u/1/