【问题标题】:Best way with javascript to turn a json object into a sorted html select使用 javascript 将 json 对象转换为排序的 html 选择的最佳方法
【发布时间】:2014-10-15 09:51:25
【问题描述】:

将 json 对象转换为已排序的 HTML 选择(仅限直接 javascript)的最佳方法是什么?

json 的格式可以根据需要进行更改。我一直在搜索,大多数文档都说对象键无法排序,只能对数组进行排序,但我不知道如何修改 json 的结构以使其成为数组,从而轻松排序。

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

会变成这样:

    <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>

【问题讨论】:

  • 你有没有尝试过?请发布您解决问题的尝试。
  • 创建一个(空)数组。拆分键 (group?) 末尾的数字并将其用于数组索引。填充数组。然后,使用for 循环遍历数组并写出数据。

标签: javascript html json sorting


【解决方案1】:

通过使用document.createElement 和几个for 循环,我们可以做到这一点:http://jsfiddle.net/kruduuzo/

首先,我们使用for in 循环来获取要用作 optgroup 的键的名称。然后我们使用我们刚刚发现的组名循环遍历该 optgroup 中的数组。进入后,您再执行一次for in 循环以获取值名称,然后使用它来设置textContent。然后,您只需将孩子附加到各自的父母,最后将选择附加到正文。

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);

我没有注意到你说json的格式可以改变。在这种情况下,我会做一些类似于 GravityScore 对你的 json 所做的事情。但是,如果您发现将 json 保持在相同的格式更容易,我的解决方案肯定会让您到达您需要的地方。

【讨论】:

  • 这对于创建 Select 来说是完美、直接且易于理解的。它将如何修改以处理排序?
  • @DonavonLerman 好问题...我承认我只是注意到您也希望它进行排序。我想我在这件事上开枪了。正如 GravityScore 所说,您无法以当前格式对其进行排序。你必须重新排列它。
  • 您有什么建议吗?我试过:`var json = { [ { "group3": [ {"value33": "label33"}, {"value13": "label13"}, {"value23": "label23"} ] } ], [ { "group1": [ {"value21": "label21"}, {"value31": "label31"}, {"value11": "label11"} ] } ] };
【解决方案2】:

JavaScript 中的字典无法排序,因为它们根本没有顺序的概念。我通常解决这个问题的方法是:

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

要像这样对对象进行排序,您可以使用自定义排序功能。将每个组按顺序排序:

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

要对组内的每个内容数组进行排序,您只需遍历 json 数组中的每个值,然后使用上面的另一个自定义排序函数对其内容调用 sort。有关这些的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

【讨论】:

  • 哇,这很简单。选项如何按标签排序?如果我将排序内容更改为a.content.label &lt; b.content.label,它不起作用
【解决方案3】:

我能够通过稍微修改 JSON 的结构(因为你说这没问题)并编写自定义排序函数来解决这个问题。

在这里提琴: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>

【讨论】:

  • 当我看到这样的东西时,JS就变得模糊了。这绝对是魔法的杰作。谢谢你。如果您在某处有在线小费罐,请告诉我。
  • P.S.我对其进行了修改,以便它可以处理没有 optgroup 的选择选项的 json。让我知道这是否是一个好方法。 jsfiddle.net/djlerman/gah4uxde
  • 我觉得不错。我还在上面添加了一些 cmets,希望能帮助你更好地理解代码。
猜你喜欢
  • 2014-02-11
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
  • 2011-06-09
  • 2021-10-16
  • 1970-01-01
相关资源
最近更新 更多