Jquery 在选项组中选择具有层次结构JSON的2?

Jquery 在选项组中选择具有层次结构JSON的2?,jquery,jquery-select2,Jquery,Jquery Select2,对于给定的JSON结构,如下所示: { "fruit": [ { "id": 1, "name": "Orange" }, { "id": 2, "name": "Banana" }, { "id": 3, "name": "Apple" }

对于给定的JSON结构,如下所示:

    {
    "fruit": [
        {
            "id": 1,
            "name": "Orange"
        },
        {
            "id": 2,
            "name": "Banana"
        },
        {
            "id": 3,
            "name": "Apple"
        }
    ],
    "vegetables": [
        {
            "id": 4,
            "name": "Potato"
        },
        {
            "id": 5,
            "name": "Carrot"
        },
        {
            "id": 6,
            "name": "Broccoli"
        }
    ]
}
当将此信息作为“数据”传递到select2方法中时,如何获取此信息以作为选项组进行渲染

<select>
<optgroup label="fruit">
    <option>Orange</option>
    <option>Apple</option>
    <option>Banana</option>
</optgroup>
<optgroup label="vegetable">
    <option>Potato</option>
    <option>Carrot</option>
    <option>Broccoli</option>
</optgroup>

橙色
苹果
香蕉
马铃薯
胡萝卜
西兰花
以下是解决方案:

<select class="js-example-basic-single"></select>

<script>
var data = {
    "fruit": [
        {
            "id": 1,
            "name": "Orange"
        },
        {
            "id": 2,
            "name": "Banana"
        },
        {
            "id": 3,
            "name": "Apple"
        }
    ],
    "vegetables": [
        {
            "id": 4,
            "name": "Potato"
        },
        {
            "id": 5,
            "name": "Carrot"
        },
        {
            "id": 6,
            "name": "Broccoli"
        }
    ]
};



   $().ready(function(){
var parsedJsonString = JSON.stringify(data); // get json string
var parsedJsonObject = $.parseJSON(parsedJsonString); // convert json string to object
$.each(parsedJsonObject,function(ele)
{
    $(".js-example-basic-single").append("<optgroup label='" + ele + "'>");
    $.each(parsedJsonObject[ele],function(subEle)
     {
         $(".js-example-basic-single").append("<option value='" + parsedJsonObject[ele][subEle]["id"] + "'>" + parsedJsonObject[ele][subEle]["name"] + "</option>");
    });   
    $(".js-example-basic-single").append("</optgroup>");
});


$(".js-example-basic-single").select2();

});

风险值数据={
“水果”:[
{
“id”:1,
“名称”:“橙色”
},
{
“id”:2,
“名称”:“香蕉”
},
{
“id”:3,
“名称”:“苹果”
}
],
“蔬菜”:[
{
“id”:4,
“名称”:“马铃薯”
},
{
“id”:5,
“名称”:“胡萝卜”
},
{
“id”:6,
“名称”:“西兰花”
}
]
};
$().ready(函数()){
var parsedJsonString=JSON.stringify(数据);//获取JSON字符串
var parsedJsonObject=$.parseJSON(parsedJsonString);//将json字符串转换为对象
$.each(parsedJsonObject、函数(ele)
{
$(“.js示例基本单”).append(“”);
$.each(parsedJsonObject[ele],function(subEle)
{
$(“.js示例基本单”).append(“+parsedJsonObject[ele][subEle][“name”]+”);
});   
$(“.js示例基本单”).append(“”);
});
$(“.js示例基本单”).select2();
});