如何通过两个键来订购JSON对象?

Sco*_*try 9 javascript json

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

{
   "GROUPID":3169675,
   "LASTNAME":"Chantry"
}
Run Code Online (Sandbox Code Playgroud)

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

任何帮助都会很棒.

Mic*_*Mic 38

以下是对具有多个列的对象数组进行排序的通用方法:

var arr = [
    { id:5, name:"Name3" },
    { id:4, name:"Name1" },
    { id:6, name:"Name2" },
    { id:3, name:"Name2" }
],

// generic comparison function
cmp = function(x, y){
    return x > y ? 1 : x < y ? -1 : 0; 
};

//sort name ascending then id descending
arr.sort(function(a, b){
    //note the minus before -cmp, for descending order
    return cmp( 
        [cmp(a.name, b.name), -cmp(a.id, b.id)], 
        [cmp(b.name, a.name), -cmp(b.id, a.id)]
    );
});
Run Code Online (Sandbox Code Playgroud)

要添加其他列以进行排序,可以在数组比较中添加其他项.

arr.sort(function(a, b){
    return cmp( 
        [cmp(a.name, b.name), -cmp(a.id, b.id), cmp(a.other, b.other), ...], 
        [cmp(b.name, a.name), -cmp(b.id, a.id), cmp(b.other, a.other), ...]
    );
});
Run Code Online (Sandbox Code Playgroud)

编辑:根据下面的@PhilipZ评论,JS中的数组比较将它们转换为由逗号分隔的字符串.


Anu*_*rag 10

假设你有一个对象数组:

var data = [
    { "GROUPID":3169675, "LASTNAME":"Chantry" },
    { "GROUPID":3169612, "LASTNAME":"Doe" },
    ...
];
Run Code Online (Sandbox Code Playgroud)

您可以使用自定义比较器进行排序.首先按顺序排序GROUPID,然后通过LASTNAME比较两个对象的逻辑:

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;
Run Code Online (Sandbox Code Playgroud)

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

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

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