Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var myObject = [{"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}]}]}]}];
- function iterateJson(obj) {
- $.each(obj, function(key, val) {
- if(val && typeof val === "object") { // object, call recursively
- iterateJson(val);
- } else {
- console.log(key + ' => ' + val);
- }
- });
- }
- iterateJson(myObject);
- <!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+'<ul>';
- if(typeof(value.children) == 'object'){
- $.each(value.children, function(keyId, val){
- htmlElem += '<li>'+val.id+'</li>';
- });
- }
- htmlElem += '</ul></li>';
- $('.showResult').html(htmlElem);
- });
- htmlElem += '</ul>';
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement