Vinci Da Vinci Da - 6 months ago 142
PHP Question

How to add order list into jQuery Nestable JSON serialize

I've using jQuery Nestable menu from http://robertan.com/blog/?p=108

But I want make an enhancement on the JSON serialize from

[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5}]}]


become

[{"id":1,"order":1},{"id":2,"order":2},{"id":3,"order":3,"children":[{"id":4,"order":1},{"id":5,"order":2}]}]


Any suggestion?

I don't know javascript well,but PHP is OK~

Answer

This gives your expected result, find the inline comments for more details

<script>
$(document).ready(function(){

//create the json object
var menu = $.parseJSON('[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5}]}]');

//final result variable menu
var final_menu = [];

//initial variable
var i = 1;

//process each element
$.each(menu, function(index, value){

//local variable
var item = {};

//type of validation
if(typeof(value.children) !== 'undefined')
{
    var j = 1;

    item['id'] = value.id;
    item['order'] = i;
    item['children'] = [];

    //process each children
    $.each(value.children, function(index1, value1){

        var child = {};

        child['id'] = value1.id;
        child['order'] = j;

        item['children'].push(child);

        j++; 

    });
}
else
{
    item['id'] = value.id;
    item['order'] = i; 
}

//create the final menu
final_menu.push(item);

i++;

});

console.log(final_menu);

});
</script>
Comments