jquery - How to sort values from json array follow ul,li -
i have json string. how sort attribute values json follow ul,li html?
[{"id":1}, {"id":2,"children":[{"id":3}, {"id":4}, {"id":5,"children":[{"id":6}, {"id":7}, {"id":8} ] }, {"id":9}, {"id":10,"children":[{"id":11,"children":[{"id":12}]}]}]} ]
try below
<!doctype html> <html> <title>stack jquery</title> <link rel="stylesheet" href="../repo/css/bootstrap.css" type="text/css" /> <script src="https://code.jquery.com/jquery-2.1.3.js"></script> <script src="../repo/js/bootstrap.js"></script> <script src="../repo/js/jquery.validate.js"></script> <head></head> <body> <div class="showresult"> </div> <script> var data = [{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10,"children":[{"id":11,"children":[{"id":12}]}]}]}] var htmlelem = '<ul>'; $.each(data, function(key, value){ htmlelem += '<li>'+value.id if(typeof(value.children) != "undefined" && typeof(value.children) == 'object'){ htmlelem += '<ul>'+extractelements(value.children)+'</ul>' } htmlelem += '</li>'; $('.showresult').html(htmlelem); }); htmlelem += '</ul>'; function extractelements(data){ var childelem = ''; $.each(data, function(ke, value){ if(value.id != 'undefined') { childelem += '<li>'+value.id if(typeof(value.children) != 'undefined' && typeof(value.children) == 'object'){ childelem += '<ul>'+extractelements(value.children)+'</ul>'; } childelem += '</li>'; } }); return childelem; } </script> </body> </html>
Comments
Post a Comment