简体   繁体   English

用javascript将json对象变成排序的html select的最佳方法

[英]Best way with javascript to turn a json object into a sorted html select

What would be the best way to turn a json object into a sorted HTML select (straight javascript only)? 将json对象转换为排序的HTML选择(仅用于纯JavaScript)的最佳方法是什么?

The format of the json can change if needed. 如果需要,可以更改json的格式。 I have been searching and most documentation says that object keys can not be sorted only arrays can be sorted, but I couldn't figure out how I would modify the structure of the json to make it an array and therefore easily sortable. 我一直在搜索,大多数文档都说不能对对象键进行排序,而只能对数组进行排序,但是我无法弄清楚如何修改json的结构以使其成为数组并因此易于排序。

var json = {
                "group3": [
                  {"value33": "label33"},
                  {"value13": "label13"},
                  {"value23": "label23"}
                ],
                "group1": [
                  {"value21": "label21"},
                  {"value31": "label31"},
                  {"value11": "label11"}
                ],
                "group2": [
                  {"value22": "label22"},
                  {"value12": "label12"},
                  {"value32": "label32"}
                ]
              };

Will become this: 会变成这样:

    <select multiple="multiple">
      <optgroup label="Group 1">
        <option value="value11">Label 11</option>
        <option value="value21">Label 21</option>
        <option value="value31">Label 31</option>
      </optgroup>
      <optgroup label="Group 2">
        <option value="value12">Label 12</option>
        <option value="value22">Label 22</option>
        <option value="value32">Label 32</option>
      </optgroup>
      <optgroup label="Group 3">
        <option value="value13">Label 13</option>
        <option value="value23">Label 23</option>
        <option value="value33">Label 33</option>
      </optgroup>
    </select>

I was able to solve this by modifying the structure of your JSON slightly (since you said this was OK) and writing a custom sorting function. 我可以通过稍微修改JSON的结构(因为您说没问题)并编写自定义排序功能来解决此问题。

Fiddle here: http://jsfiddle.net/9urusm5p/2/ 在这里提琴: http : //jsfiddle.net/9urusm5p/2/

<html>
    <head>
        <script>

            //take an object and loop through all the properties
            //each property goes into an array and is sorted
            //loop through the sorted array and build an output array of objects
            //objects in output have 2 properties
            //key = original property name, value = original property value
            function createSortedArray(obj) {
                var returnArray = [];
                var sortingArray = [];
                for(var property in obj) {
                    sortingArray.push(property);
                }
                sortingArray.sort();
                for(var index = 0; index < sortingArray.length; index++) {
                    var property = sortingArray[index];
                    var newObject = {};
                    newObject.key = property;
                    newObject.value = obj[property];
                    returnArray.push(newObject);
                }
                return returnArray;
            }

            window.onload = function() {
                var json = {
                                "group3": {
                                  "value33": "label33",
                                  "value13": "label13",
                                  "value23": "label23"
                                },
                                "group1": {
                                  "value21": "label21",
                                  "value31": "label31",
                                  "value11": "label11"
                                },
                                "group2": {
                                  "value22": "label22",
                                  "value12": "label12",
                                  "value32": "label32"
                                }
                              };

                //sort source object with function above and loop through results
                var sortedGroups = createSortedArray(json);
                for(var index = 0; index < sortedGroups.length; index++) {
                    var group = sortedGroups[index];

                    //create optgroup tag and assign label property
                    var optGroup = document.createElement("optgroup");
                    optGroup.label = group.key;

                    //sort the properties of the current group using our function again
                    var optionArray = createSortedArray(group.value);
                    for(var optionIndex = 0; optionIndex <  optionArray.length; optionIndex++ ) {
                        //options are now sorted, just add to the optgroup
                        var option = optionArray[optionIndex];
                        var opt = document.createElement("option");
                        opt.value = option.key;
                        opt.textContent  = option.value;
                        optGroup.appendChild(opt);
                    }

                    //add optgroup to select tag
                    document.getElementById("select").appendChild(optGroup);
                }
            }
        </script>
    </head>
    <body>
        <select id="select" multiple="multiple" style="height:300px;width:100px;"></select>
    </body>
</html>

By using document.createElement , and a few for loops, we can accomplish this: http://jsfiddle.net/kruduuzo/ 通过使用document.createElement和一些for循环,我们可以完成此任务: http : //jsfiddle.net/kruduuzo/

First we use a for in loop to get the names of the keys to use as the optgroup. 首先,我们使用for in循环获取用作optgroup的键的名称。 Then we loop through the array within that optgroup, using the group name that we just discovered. 然后,使用刚刚发现的组名在该optgroup中的数组中循环。 Once inside, you then do another for in loop to get the value name, and then use it to set the textContent . 进入内部之后,您for in循环中执行另一个操作以获取值名称,然后使用它来设置textContent Then you simply append the children to their respective parents, and finally the select to the body. 然后,您只需将孩子附加到其各自的父母,最后将选择附加到身体。

var body = document.getElementsByTagName("body")[0];

var select = document.createElement("select");
select.multiple = true;

for (group in json) {
    var optgroup = document.createElement("optgroup");
    optgroup.label = group;
    var i = 0, count = json[group].length;
    for (i; i < count; i++) {
        var opt = document.createElement("option");
        for (value in json[group][i]) {
            opt.value = value;
            opt.textContent = json[group][i][value];
        }
        optgroup.appendChild(opt);
    }
    select.appendChild(optgroup);
}

body.appendChild(select);

I didn't notice that you said that the format of the json could change. 我没有注意到您说json的格式可以更改。 In that case, I'd do something similar to what GravityScore did to your json. 在这种情况下,我会执行类似于GravityScore对您的json所做的操作。 However, if you find it easier to keep your json in the same format, my solution definitely gets you where you need to be. 但是,如果您发现将json保持相同的格式更加容易,那么我的解决方案肯定可以满足您的需求。

Dictionaries in JavaScript can't be sorted because they have no concept of order at all. 无法对JavaScript中的字典进行排序,因为它们根本没有顺序的概念。 The way I usually solve this is something along the lines of: 我通常解决此问题的方式大致如下:

var json = [
  {
    "name": "group1",
    "content": [
      {"value": "value13", "label": "label13"},
      {"value": "value11", "label": "label33"},
      ...
    ],
  },
  {
    "name": "group2",
    "content": [
      ...
    ]
  },
  ...
}

To sort an object like this, you can use a custom sorting function. 要对这样的对象进行排序,可以使用自定义排序功能。 To sort each group into order: 将每个组按顺序排序:

json.sort(function(a, b) {
  if (a.name < b.name) {
    return -1;
  } else if (a.name > b.name) {
    return 1;
  } else {
    return 0;
  }
}

To sort each content array inside a group you can just loop over each value in the json array, and call sort on its content using another custom sorting function like above. 排序一组你可以在JSON数组中的每个值循环,并调用内部的每个内容数组sort上采用与上述其他自定义排序功能的内容。 For more info on these: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort 有关这些的更多信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM