如何通过两个键来订购JSON对象? [英] How to order a JSON object by two keys?

查看:74
本文介绍了如何通过两个键来订购JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象,我想首先按一个键排序,然后按第二个键排序,类似于SQL中两列的排序。以下是我将拥有的JSON示例:

I have a JSON object that I want to sort by one key first, then by a second key similar to ordering by two columns in SQL. Here is a sample of the JSON I would have:

{
   "GROUPID":3169675,
   "LASTNAME":"Chantry"
}

我想订购所有结果GROUPID然后是LASTNAME。我已经使用JSON排序函数按一个键排序,但不是多个。

I would like to order all the results by the GROUPID and then by LASTNAME. I've used the JSON sort function to sort by one key but not multiple.

任何帮助都会很棒。

推荐答案

假设你有一个对象数组:

Assuming you have an array of objects:

var data = [
    { "GROUPID":3169675, "LASTNAME":"Chantry" },
    { "GROUPID":3169612, "LASTNAME":"Doe" },
    ...
];

您可以使用自定义比较器进行排序。要先按 GROUPID 进行排序,再按 LASTNAME 进行排序,比较两个对象的逻辑是:

You can use a custom comparator to do the sorting. To sort first by GROUPID, and then by LASTNAME, the logic to compare two objects would be:

if GROUPID of first is smaller than second
    return -1;
else if GROUPID of first is larger than second
    return 1;
else if LASTNAME of first is smaller than second
    return -1;
else if LASTNAME of first is larger than second
    return 1;
else
    return 0;

要对对象数组进行排序,请使用上面的算法并在数组上调用sort方法。排序完成后, data 应该具有所需排序顺序的元素。

To sort the object array, use the above algorithm and call the sort method on the array. After sorting is done, data should have the elements in required sorted order.

data.sort(function(a, b) {
    // compare a and b here using the above algorithm
});

这是另一个非常类似的问题我最近回答。它是关于使用jQuery对多个列进行排序,但您可以轻松地删除jQuery部分。它提供了一些可自定义的方法,可以扩展到多个列。

Here's another very similar question I answered recently. It's regarding sorting on multiple columns using jQuery, but you can strip out the jQuery part easily. It presents some customizable approaches which can extend to multiple columns.

这篇关于如何通过两个键来订购JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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