对于给定的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>
答案 0 :(得分:1)
以下是解决方案:
<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();
});