1- Iterative arrays using forEach
2- check the presence of keys in dictionaries using object.hasOwnProperty
3- create html elements with $("< type-of-element >")
4- build a string in the desired format.
You can try this script:
var data= [ { "country": "India", "state": [ { "name": "Delhi", "capital": "New Delhi" }, { "name": "Tamilnadu", "capital": "Chennai" } ] }, { "country": "USA", "state": [ { "name": "Alabama", "capital": "Montgomery" }, { "name": "Alaska", "capital": "Juneau" } ] } ] var to_append = $("body") //your append selector if(data && data.length>0){ var outer_ul = $("<ul>") data.forEach(function(e,i){ if(e.hasOwnProperty("country")){ outer_ul.append($("<li>", {text : e['country']})) } if(e.hasOwnProperty("state")){ var inner_ul = $("<ul>") e['state'].forEach(function(__e,__i){ if(__e.hasOwnProperty('capital')){ inner_ul.append($("<li>", {text : "State "+(__i+1) + " : " + __e['capital']})) } }) outer_ul.append(inner_ul) } }) to_append.append(outer_ul) }
this will result in html output:
<ul> <li>India</li> <ul><li>State 1 : New Delhi</li><li>State 2 : Chennai</li></ul> <li>USA</li> <ul><li>State 1 : Montgomery</li><li>State 2 : Juneau</li></ul> </ul>
xecgr source share