Kitof
Kitof

Reputation: 35

Nested json, and recursive $.Each()

I've got a nested JSON like this :

[{
"1": {
    "name": "Mobile"
},
"5": {
    "name": "Savings",
    "childs": {
        "27": {
            "name": "Children"
        }
    }
},
"6": {
    "name": "Pro Expenses"
},
"7": {
    "name": "Salary",
    "childs": {
        "143": {
            "name": "Salary Savings"
        }
    }
},
"8": {
    "name": "Food",
    "childs": {
        "13": {
            "name": "Lunch Food",
            "childs": {
                "53": {
                    "name": "Coffee"
                }
            }
        },
        "91": {
            "name": "Canteen"
        },
        "93": {
            "name": "Market"
        }
    }
}]

I'd like to create a nested select with optgroup and option like this :

<SELECT>
<OPTION value="1">Mobile</OPTION>
<OPTGROUP name="Savings">
    <OPTION value="27">Children</OPTION>
</OPTGROUP>
<OPTION value="6">Pro Expenses</OPTION>
<OPTGROUP name="Salary">
    <OPTION value="143">Salary Savings</OPTION>
</OPTGROUP>
<OPTGROUP name="Food">
    <OPTGROUP name="Lunch Food">
        <OPTION value="53">Coffee</OPTION>
    </OPTGROUP>
    <OPTION value="91">Canteen</OPTION>
    <OPTION value="93">Market</OPTION>
</OPTGROUP>
</SELECT>

I know that nested OPTGROUP is not valid. But this is not the point, that I want to discuss here. ;)

My Jquery code below isn't working because of the third parameters of each which isn't supported.

$.getJSON("/?act=get_json_data",{data:'categories'}, function(json) {
    var select = $('#categories');
    $.each(json, function add_optgroup(k, item, parent=select) {
        if (typeof(item.childs) !== 'undefined') {
            var group = $('<optgroup>',{label:item.name});
            $.each(item.childs, add_optgroup(ck, citem, group));
            group.appendTo(parent);
        } else {
            $("<option/>",{value:k,text:item.name})
                    .appendTo(parent);
        }
    });

I tried a lot of solutions, but because of the ".appendTo()", I need the parent, and each doesn't allow a third parameter.

Any help is welcome ;)

Upvotes: 2

Views: 213

Answers (1)

user2404501
user2404501

Reputation:

Use another nested function to bridge the gap between the 3-arg function call you want and the inner each callback:

$.each(item.childs, function(ck, citem) { add_optgroup(ck, citem, group) });

This function gets the key/value arguments from each and adds the third argument group which it has access to as part of the enclosing scope.

Upvotes: 1

Related Questions