如何将JSON逗号分隔的值附加到选择框?

时间:2018-10-09 07:12:46

标签: jquery json

我得到一个JSON对象,如下所示:

{
    id: "3",
    restaurant_name: "Annapurna Restaurant",
    sub_category_id: "2,3",
    sub_cat: "Meals,Tiffins"
}

我需要将sub_category_idsub_cat附加到选择框,例如:

$("#id").append("<option value='" + sub_category_id + "'>" + sub_cat + "</option>");

如何将这些数据附加到选择框?

2 个答案:

答案 0 :(得分:0)

我不会像这样遍历JSON,而是这样:

{
    id: "3", 
    restaurant_name: "Annapurna Restaurant",
    categories:
    [
        { id: "2", cat: "Meals" },
        { id: "3", cat: "Tiffins" }
    ]
}

如果您别无选择,则可以拆分类别ID和名称属性,然后只需调用对象名称即可。例如:MyObject.SomeProperty

let MyJson = {
  id: "3", 
  restaurant_name: "Annapurna Restaurant", 
  sub_category_id: "2,3", 
  sub_cat: "Meals,Tiffins"
};


let ids = MyJson.sub_category_id.split(',');
let cats = MyJson.sub_cat.split(',');

for (let i = 0; i < ids.length; ++i)
{
    if (i < cats.length)
        $("#id").append("<option value='" + ids[i] + "'>" + cats[i] + "</option>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="id"></select>

答案 1 :(得分:0)

我认为您正在寻找类似的东西。 (我从您对@Cid ansawr的评论中了解了)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="id"></select>



<script>

var MyJson = jQuery.parseJSON('{ "id": "3",  "restaurant_name": "Annapurna Restaurant",  "sub_category_id": "2,3",  "sub_cat": "Meals,Tiffins"}');;
var cat_id = MyJson.sub_category_id.split(',');
var sub_cat = MyJson.sub_cat.split(',');

$(cat_id).each(function(index, el) {
	$("#id").append("<option value='" + el + "'>" + sub_cat[index] + "</option>");
});

</script>