简体   繁体   中英

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. Basically the user will click a state and the state laws will append underneath the map. Right now my JSON tree looks like:

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. I need the abbreviated state name because that is the data that the map API spits out when a state is clicked. 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. 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.

 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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