简体   繁体   English

遍历嵌套的对象文字数据

[英]Traverse nested Object Literal data

Been looking through the forums and none of the solutions that I have seen have worked for my case unless I am doing it wrong. 一直在浏览论坛,除非我做错了,否则我所见的解决方案都无法解决我的问题。 I am trying to list out data for different states that is connected to a jQuery map plugin. 我试图列出连接到jQuery地图插件的不同状态的数据。 Basically the user will click a state and the state laws will append underneath the map. 基本上,用户将单击一个州,并且州法律将附加在地图下方。 Right now my JSON tree looks like: 现在,我的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...
}

Using the answer to the question here , I can dive into tier 2 nested Data, but the entry point for the state seems to be the hold up. 使用此处问题的答案,我可以深入了解第2层嵌套数据,但是该状态的切入点似乎是阻碍。 I need the abbreviated state name because that is the data that the map API spits out when a state is clicked. 我需要缩写的州名,因为这是单击状态时map API吐出的数据。 Any idea of what other steps might need to be implemented in order to make this work? 为了使这项工作可能需要执行哪些其他步骤? Seems like there are no answers for finding an object within an object. 似乎没有找到对象内对象的答案。 Thanks in advance! 提前致谢!

EDIT: I found the exact answer I was looking for once I realized I was clumsy and that this was an Object Literal, and not JSON. 编辑:一旦我意识到自己笨拙,并且这是对象文字,而不是JSON,我便找到了所需的确切答案。 I found the answer here 我在这里找到答案

You just need to use Object.keys() to get the abbreviated name which is defined as properties of state object. 您只需要使用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)) 

You can iterate and get short name like this: 您可以迭代并获得如下简称:

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/ JSFiddle: https ://jsfiddle.net/12bor11u/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM