Nitish Kumar Nitish Kumar - 3 months ago 9
Javascript Question

how to recurse through child nodes and output as json?

I'm having nested un-ordered list with childrens, I'm trying to store all the data from the list into JSON format data:

Following is my HTML code:

<nav id="nav">
<ul class="header-top-nav">
<li>
<a href="index.html">Home</a>
<ul>
<li><a href="subhome1.html">Home 1</a>
<ul>
<li><a href="subsubhome1.html">Sub Home</a></li>
</ul>
</li>
<li><a href="subhome2.html">Home 2</a></li>
<li><a href="subhome3.html">Home 3</a></li>
</ul>
</li>
</ul>
</nav>


My JQuery:

content = [];
$('nav > ul').find('li').each( function () {

pages = {};
function menu() {
pages['pagelink'] = $(this).children('a').attr('href');
pages['pagename'] = $(this).children('a').text();
var submenucheck = $(this).children('ul').length;
if(submenucheck){
pages['submenu'] = [];
menu();
}
else{
pages['submenu'] = "NULL";
}
contents.push(pages);
}menu();

});


I want to have data format to be like this:

{
"pages": [
{
"pagelink": "index.html",
"pagename": "Home",
"submenu": [
{
"pagelink": "subhome1.html",
"pagename": "Home 1",
"submenu": [
{
"pagelink": "subsubhome1.html",
"pagename": "Sub Home",
"submenu": "NULL"
}
]
},
{
"pagelink": "subhome2.html",
"pagename": "Home 2",
"submenu": "NULL"
},
{
"pagelink": "subhome3.html",
"pagename": "Home 3",
"submenu": "NULL"
}
]
}
]
}


Please help me out to achieve this.

JAG JAG
Answer

try this one

var results = { };

function getData(ul) {
    var data = []
    ul.children('li').each(function() {
        var li = $(this),
            subData = {},
            a = li.children('a'),
            child = li.children('ul');
        subData['pagelink'] = a.attr('href');
        subData['pagename'] = a.text();
        if(child.length) 
            subData['submenu'] = getData(child);	
        data.push(subData);
    })
    return data;
}
results.pages = getData($('nav > ul'));
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="nav">
<ul class="header-top-nav">
    <li>
        <a href="index.html">Home</a>
        <ul>
            <li><a href="subhome1.html">Home 1</a>
                <ul>
                    <li><a href="subsubhome1.html">Sub Home</a></li>
                </ul>
            </li>
            <li><a href="subhome2.html">Home 2</a></li>
            <li><a href="subhome3.html">Home 3</a></li>
        </ul>
    </li>
</ul>
</nav>