Select2 Multi level Opt Groups

HTML flattens multiple level opt-groups, so to get multiple levels in Select2, the data must be passed as JSON to build the desired select2 element.

HTML

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select id="test"></select>

JavaScript

$(document).ready(function() {
$('#test').select2({
    placeholder: 'Search for an option',
    multiple: true,
    data: [
        {
            text: 'Level_1', 
            children: [
            		{
                    id: 'Level1Opt0', text: 'Main Level option 1'
                },
                {
                    id: 'Level1Opt1', text: 'Main Level option 2'
                },
                {
                    text: 'Level_2', children: [
                        {
                            id: 'Level2Opt0', text: 'Sub Option 1'
                        },
                        {
                            id: 'Level2Opt1', text: 'Sub Option 2'
                        }
                    ]
                }
             ]
         }
    ],
});    
});