Slimen Tunis Slimen Tunis - 7 months ago 15
Javascript Question

Save ul list into json object

I'm trying to save a list into

json
object by looping through it using a recursive function, so this is what I did so far:

My list:

<ul id="Menu">
<li>Menu
<ul>
<li>Test 1</li>
<li>Test 2
<ul>
<li>Sub test 2/1</li>
<li>Sub test 2/2</li>
<li>Sub test 2/3</li>
</ul>
</li>
<li>Test 3</li>
<li>Test 4</li>
</ul>
</li>
<li>Menu2</li>
</ul>


My script:


<script>
jQuery(document).ready(function(){
item = {};
buildMenu($('#Menu'), item);
menu.push(item);
console.log(JSON.stringify(menu));
});
var menu = [];

function buildMenu(ul, item){
var children = [];
ul.find('li').each(function(){
var current = $(this);
if(current.find('ul').length > 0){
var newItem = {};
buildMenu(current.find('ul'), newItem);
children.push(newItem);
}else{
children.push(current.text());
}
});

var txt = $(this).text();
console.log('pushing into: '+txt);
item[txt] = children;
}
</script>


I want to save each menu and it's children inside it as json objects and send it to php but I'm having wrong output:

[{"MenuTest 1Test 2Sub test 2/1Sub test 2/2Sub test 2/3Test 3Test 4Menu2":[{"Test 1Test 2Sub test 2/1Sub test 2/2Sub test 2/3Test 3Test 4":["Test 1",{"Sub test 2/1Sub test 2/2Sub test 2/3":["Sub test 2/1","Sub test 2/2","Sub test 2/3"]},"Sub test 2/1","Sub test 2/2","Sub test 2/3","Test 3","Test 4"]},"Test 1",{"Sub test 2/1Sub test 2/2Sub test 2/3":["Sub test 2/1","Sub test 2/2","Sub test 2/3"]},"Sub test 2/1","Sub test 2/2","Sub test 2/3","Test 3","Test 4","Menu2"]}]


What's wrong with my function ?

Answer

is this what you are looking for?

var menu = [];
$(document).ready(function(){
    item = {};
    buildMenu($('#Menu'), item);
    menu.push(item);
    console.log(menu);  
});


function buildMenu(ul, item){
    var children = [];
    ul.children('li').each(function(){
        var current = $(this);
        if(current.children('ul').length > 0){
            var newItem = {};
            buildMenu(current.children('ul'), newItem);
            children.push(newItem);
        }else{
            children.push(current.text());
        }
    })

var txt = ul.parent().html();
txt = txt.replace(/\<ul.*[\s\S]*\<\/ul\>/g,"").trim();
console.log(txt);
item[txt] = children;      
}

you should only select immediate children.

fiddle: https://jsfiddle.net/nsj3gqt5/1/