Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery JavaScript中的GroupBy将JSON数据分组并填充到optgroup上_Jquery_Json_Optgroup - Fatal编程技术网

Jquery JavaScript中的GroupBy将JSON数据分组并填充到optgroup上

Jquery JavaScript中的GroupBy将JSON数据分组并填充到optgroup上,jquery,json,optgroup,Jquery,Json,Optgroup,我有点迷路了。 我得到了这个JSON: [{ "id": "210", "name": "Name 1", "category": "Category 1" }, { "id": "187", "name": "Name 2", "category": "Category 1" }, { "id": "186", "name": "Name 3", "category": "Category 1" }, { "id"

我有点迷路了。 我得到了这个JSON:

[{
    "id": "210",
    "name": "Name 1",
    "category": "Category 1"
}, {
    "id": "187",
    "name": "Name 2",
    "category": "Category 1"
}, {
    "id": "186",
    "name": "Name 3",
    "category": "Category 1"
}, {
    "id": "185",
    "name": "Name 4",
    "category": "Category 1"
}, {
    "id": "184",
    "name": "Name 5",
    "category": "Category 1"
}, {
    "id": "183",
    "name": "Name 6",
    "category": "Category 1"
}, {
    "id": "182",
    "name": "Name 7",
    "category": "Category 1"
}, {
    "id": "181",
    "name": "Name 8",
    "category": "Category 2"
}, {
    "id": "180",
    "name": "Name 9",
    "category": "Category 3"
}, {
    "id": "178",
    "name": "Name 10",
    "category": "Category 2"
}]
我想把所有这些都放在一个带有选项和optgroup的select中。实际上,optgroup应该是category

我想要这样的东西:

<select name="products" class="product" id="product">
<optgroup label="Category 1">
    <option value="210">Name 1</option>
    <option value="187">Name 2</option>
    <option value="186">Name 3</option>
    <option value="185">Name 4</option>
    ...
</optgroup>
<optgroup label="Category 2">
    <option value="181">Name 8</option>
    <option value="178">Name 10</option>
</optgroup>
<optgroup label="Category 3">
    <option value="180">Name 9</option>
</optgroup>

名字1
名称2
名字3
名字4
...
姓名8
名字10
名字9

今天我之所以这么做,是因为我挣扎得太多了:

$(document).ready(function () {
    $.getJSON("5.php", {
        val: $(this).val()
    }, function (data) {
        $.each(data, function (i, item) {
            $("<option/>").attr("value", item.id).append(item.name).appendTo("optgroup");
        });
    });
});
$(文档).ready(函数(){
$.getJSON(“5.php”{
val:$(this.val()
},函数(数据){
$。每个(数据、功能(i、项){
$(“”).attr(“value”,item.id).append(item.name).appendTo(“optgroup”);
});
});
});
正如您所看到的,没有optgroup:) 有办法做到这一点吗? 我也可以修改我的JSON,如果它可以使它更容易


谢谢您的帮助。

假设optgroups已经存在,请更改此

.appendTo("optgroup")
对此

.appendTo("optgroup[label='" + item.category + "']");


如果它们不存在,则需要创建它们,不过我建议重新构造JSON响应,使每个项都嵌套在适当的类别下

像这样

{
    "Category 1":[
        {"id": "210","name": "Name 1"},
        {"id": "187","name": "Name 2"},
        {"id": "186","name": "Name 3"},
        {"id": "185","name": "Name 4"},
        {"id": "184","name": "Name 5"},
        {"id": "183","name": "Name 6"},
        {"id": "182","name": "Name 7"}
    ],
    "Category 2":[
        {"id": "181","name": "Name 8"},
        {"id": "178","name": "Name 10"}
    ],
    "Category 3": [
        {"id": "180","name": "Name 9"}
    ]
}
所以你可以这样做:

var product = $('#product');

$.each(data, function (key, cat) {
    var group = $('<optgroup>',{label:key});

    $.each(cat,function(i,item) {
        $("<option/>",{value:item.id,text:item.name})
            .appendTo(group);
    });

    group.appendTo( product );
});
var-product=$(“#product”);
$。每个(数据、功能(键、类别){
变量组=$('',{label:key});
$。每个(类别、功能(i、项目){
$(“”,{value:item.id,text:item.name})
.附属于(组);
});
组。附录(产品);
});

如果我是你,我会使用一个名为的小型库对返回的数据进行分组,以更简单的表示形式返回

请参阅下面的代码,您也可以看到此代码:

var groupData = _.groupBy(data, function (obj) {
    return obj.category;
});

var optGroups = [];
for (var key in groupData) {
    if (groupData.hasOwnProperty(key)) {
        var optGroup = $("<optgroup></optgroup>");
        optGroup.attr("label", key);
        var currentGroup = groupData[key];
        for (var i = 0; i < currentGroup.length; i++) {
            $("<option />").attr("value", currentGroup[i].id).html(currentGroup[i].name).appendTo(optGroup);
        }
        optGroups.push(optGroup);
    }
}

for(var i = 0; i < optGroups.length; i++) {
    $("#products").append(optGroups[i]);
}
用法:

var groupData = groupBy(data, function (obj) {
    return obj.category;
});

如果您希望保持JSON格式不变,下面将回答您的问题:

//Loop through the json, get distinct category names, and append them as optgroup to the select dropdown
var categories = [];
$.each(data, function(index, item) {
    if ($.inArray(item.category, categories) == -1) {
        categories.push(item.category);
        var optgroupId = "cat-" + item.category.replace(/\s/g, "");
        $('#id_of_select_dropdown').append('<optgroup id ="'+optgroupId+'"label="'+item.category+'">');
    }
});
// append the options to their corresponding optgroups
$.each(data.response, function(index, item) {
    var optgroupId = "cat-" + item.category.replace(/\s/g, "");
    $('#'+optgroupId).append('<option>' + item.name + '</option>');
});
//遍历json,获取不同的类别名称,并将它们作为optgroup附加到select下拉列表中
var类别=[];
$。每个(数据、功能(索引、项目){
如果($.inArray(item.category,categories)=-1){
类别。推送(项目。类别);
var optgroupId=“cat-”+item.category.replace(/\s/g,”);
$(“#id_of_select_dropdown”).append(“”);
}
});
//将选项附加到相应的optgroup
$.each(data.response,函数(索引,项){
var optgroupId=“cat-”+item.category.replace(/\s/g,”);
$('#'+optgroupId).append(''+item.name+'');
});

希望这有帮助

我知道这条线很旧,但我需要类似的东西,于是我想出了这个。它会在需要时自动添加optgroup,并使用选项填充它们。另外,它在有optgroups和没有optgroups时都有效

var-select=$(“#产品”);
$。每个(数据、功能(键、类别){
var option=“”+类别名称+”;
//如果我们有一个category属性,请将此项添加到optgroup
if(分类为hasOwnProperty(“类别”)){
var组=类别;
//如果此optgroup尚未存在,请添加它
if(选择.find(“optgroup[label='”+group+']”)。长度==0){
选择。追加(“”);
}
select.find(“optgroup[label='”+group+']”).append(选项);
//没有类别,没有optgroup。将此添加为简单选项
}否则{
选择。追加(选项);
}        
});

epic用户名是我唯一要说的。@donutdan4114谢谢。要么就是“看着我!看着我!”。多谢!!我已经修改了我的JSON并按照你说的做了!它工作得很好!或者,可以使用原始集合上的map/reduce来获取组列表,作为种子机。。。同样的,很好的建议。@Tracker1:回顾我的第二个解决方案,我发现它有缺陷。我也应该将类别结构化为对象数组,因为枚举的顺序不能保证。如果您愿意,可以随意添加更多解决方案,如map/reduce。
//Loop through the json, get distinct category names, and append them as optgroup to the select dropdown
var categories = [];
$.each(data, function(index, item) {
    if ($.inArray(item.category, categories) == -1) {
        categories.push(item.category);
        var optgroupId = "cat-" + item.category.replace(/\s/g, "");
        $('#id_of_select_dropdown').append('<optgroup id ="'+optgroupId+'"label="'+item.category+'">');
    }
});
// append the options to their corresponding optgroups
$.each(data.response, function(index, item) {
    var optgroupId = "cat-" + item.category.replace(/\s/g, "");
    $('#'+optgroupId).append('<option>' + item.name + '</option>');
});
var select = $('#product');

$.each(data, function (key, cat) {
    var option = "<option value='"+cat.id+"'>"+cat.name+"</option>";

    // If we ave a category property, add this item to an optgroup
    if (cat.hasOwnProperty("category")) {
        var group = cat.category;

        // If this optgroup is not already present, add it
        if (select.find("optgroup[label='" + group + "']").length === 0) {
            select.append("<optgroup label='" + group + "' />");
        }

        select.find("optgroup[label='" + group + "']").append(option);

    // No category, no optgroup. Add this as simple option
    } else {
        select.append(option);
    }        
});