按值对 JSON 进行排序 [英] Sorting JSON by values

查看:60
本文介绍了按值对 JSON 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 JSON 对象,如下所示:

I have a very simple JSON object like the following:

{
   "people":[
      {
         "f_name":"john",
         "l_name":"doe",
         "sequence":"0",
         "title":"president",
         "url":"google.com",
         "color":"333333"
      },
      {
         "f_name":"michael",
         "l_name":"goodyear",
         "sequence":"0",
         "title":"general manager",
         "url":"google.com",
         "color":"333333"
      }
   ]
}

既然这是从我的服务器端代码返回的,我运行 jQuery.each 来形成必要的 html 并输出结果.

Now that this is returned from my server side code, I run jQuery.each to form the necessary html and output the result.

现在我正在做的是向包含我的排序信息的服务器发送 AJAX 调用......例如标题 DESC"并重新运行 SQL 查询以返回新的结果集.但我想避免这种情况,并使用 jQuery 对生成的 JSON 进行排序,以防止往返服务器和多个数据库访问.

Right now what I am doing is sending an AJAX call to the server containing my sort info... e.g. "Title DESC" and re-run an SQL query to return the new result set. But I want to avoid this and use jQuery to sort the resulting JSON to prevent round trips to the server, and multiple database access.

我如何使用 jQuery 实现这一点?

How can I achieve this using jQuery?

推荐答案

jQuery 对排序并不是特别有用,但这里有一个优雅而有效的解决方案.只需编写一个简单的 JS 函数,该函数接受属性名称和顺序(升序或降序)并使用简单的比较函数调用原生 sort() 方法:

jQuery isn't particularly helpful for sorting, but here's an elegant and efficient solution. Just write a plain JS function that takes the property name and the order (ascending or descending) and calls the native sort() method with a simple comparison function:

var people = [
    {
        "f_name": "john",
        "l_name": "doe",
        "sequence": "0",
        "title" : "president",
        "url" : "google.com",
        "color" : "333333",
    }
    // etc
];

function sortResults(prop, asc) {
    people.sort(function(a, b) {
        if (asc) {
            return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
        } else {
            return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
        }
    });
    renderResults();
}

那么:

sortResults('l_name', true);

这里玩一个工作示例.

这篇关于按值对 JSON 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆