【问题标题】:Sort and print JSON output alphabetically in Javascript在 Javascript 中按字母顺序对 JSON 输出进行排序和打印
【发布时间】:2017-07-18 17:40:06
【问题描述】:

我有一个从 JSON 数组中提取国家/地区列表的函数

function regionPlanOutput(networkGroupId) {
    document.getElementById("country_list").innerHTML = "";
    jQuery.ajax({
        type: 'GET'
        , url: regionApiURL + '/api/v4/networkGroups/' + networkGroupId + '/countries?count=500'
        , dataType: 'json'
        , success: function (networkGroup) {
            jQuery.each(networkGroup.countryList, function (i, countryList) {
                var countryName = countryList.name;
                var flag = countryList.logoUrl;
                var countrycontent = '<li>' + countryName + '</li>';
                console.log(countrycontent)
                jQuery(countrycontent).appendTo("#country_list");
            });
        }
    });
}

目前它只是按照从数组中提取它们的顺序打印列表,如何根据变量 countryName 按字母顺序对输出进行排序?

【问题讨论】:

  • 你能包括输出 JSON 的样子吗?
  • 请注意,当您到达success 时,networkGroup 参数已经是一个 JavaScript 对象,而不是 JSON。 JSON 是一种字符串格式,因此谈论 JSON 数组是不好的术语。

标签: javascript arrays json sorting object


【解决方案1】:

不要在遍历networkGroup.countryList 时修改循环内的 DOM(这会使排序更加复杂,而且无论如何在性能方面都是一个坏主意),而是在一个临时数组中捕获国家名称,对该数组进行排序,然后一次性将其放入 DOM:

success: function (networkGroup) {
    var output = []; // temporary array
    jQuery.each(networkGroup.countryList, function (i, countryList) {
        output.push('<li>'+countryList.name+'</li>'); // capture each name in the temporary array.  We'll go ahead and include the <li> tags here since it won't affect the sort order
    });
    output.sort(); // sort it
    jQuery("#country_list").append(output.join('')); // drop it into the DOM
}

【讨论】:

  • 很高兴能帮上忙!
【解决方案2】:

对返回的数组使用排序方法,默认为字母顺序,因为您正在处理数组中的字符串。

【讨论】:

    【解决方案3】:

    假设您的 networkGroup.countryList 看起来像这样:

    countryList = [
        {name: "someName", logUrl: "http://example.com"},
        // ...etc.
    ]
    

    您可以像这样按countryList.name 排序:

    countryList.sort(function(a, b){
        return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)
    })
    

    这将就地排序,因此在您运行之后,您的 countryList 将更改为排序顺序。如果您在致电jQuery.each 之前对networkGroup.countryList 进行排序,那么您应该很高兴。

    【讨论】:

      【解决方案4】:

      在您的 success 函数中,networkGroup 已经是 JavaScript object 而不是 JSON 对象。

      因此,您只需将Array.prototype.sort() 方法与您的networkGroup.countryList 数组一起使用即可获得排序后的数组。

      这应该是你的代码:

      success: function(networkGroup) {
        networkGroup.countryList = networkGroup.countryList.sort(function(a, b) {
          var nameA = a.countryName.toUpperCase();
          var nameB = b.countryName.toUpperCase();
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0;
        });
        //The rest of your code 
      }
      

      演示:

      这是一个有效的 Demo sn-p:

      var group = {
        countryList: [{
            countryName: "Vietnam",
            prop: "5224"
          },
          {
            countryName: "USA",
            prop: "000"
          },
          {
            countryName: "Palestine",
            prop: "5454"
          },
          {
            countryName: "Nigeria",
            prop: "1717"
          },
          {
            countryName: "Albania",
            prop: "54"
          },
          {
            countryName: "Belgium",
            prop: "1000"
          }
        ]
      };
      
      
      
      var sortArray = function sortArray(networkGroup) {
        networkGroup.countryList = networkGroup.countryList.sort(function(a, b) {
          var nameA = a.countryName.toUpperCase();
          var nameB = b.countryName.toUpperCase();
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0;
        });
        return networkGroup.countryList;
      }
      console.log(sortArray(group));

      【讨论】:

        猜你喜欢
        • 2019-11-22
        • 1970-01-01
        • 1970-01-01
        • 2018-12-07
        • 1970-01-01
        • 2018-12-03
        • 2019-06-30
        • 2016-12-05
        • 2011-08-29
        相关资源
        最近更新 更多