使用两个不同的排序条件对对象进行排序,这些对象不完全相同

时间:2016-05-21 23:53:44

标签: javascript sorting

/*
        I have two people
*/

var person_one= 'person_one';
var person_two= 'person_two';

/*
    This is a response I get from a server
*/

var response = [
{"key":{"name":"person_one","kind":"attrA","path":["attrA","person_one"]},"data":{"q":"3","n":"0"}},
{"key":{"name":"person_one","kind":"attrB","parent":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"path":["attrA","person_two","attrB","person_one"]},"data":{"some_data":"p"}},
{"key":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"data":{"q":"1","n":"0"}}
];

/*
    Sort the object array by the key.kind field. So all attrA will come first and then attraB
*/

function compare(a,b) {
  if (a.key.kind < b.key.kind )
    return -1;
  else if (a.key.kind  > b.key.kind)
    return 1;
  else 
    return 0;
}

response.sort(compare); //sort

console.log('Sorted response = ' + JSON.stringify(response) ); //print sorted response

这是我到目前为止的代码。发生的事情是我收到服务器的回复:

[
{"key":{"name":"person_one","kind":"attrA","path":["attrA","person_one"]},"data":{"q":"3","n":"0"}},
{"key":{"name":"person_one","kind":"attrB","parent":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"path":["attrA","person_two","attrB","person_one"]},"data":{"some_data":"p"}},
{"key":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"data":{"q":"1","n":"0"}}
]

我现在需要使用以下两个条件对此响应进行排序:

  • 第一个条件是按照代码所使用的key.kind属性对其进行排序。所有attraA都需要先显示,然后attraB

  • 第二个条件是在按key.kind进行排序之后,然后需要按名称对其进行排序。所以person_one总是会出现在person_two之前(这些只是假名来表示概念,但实际名称可能就像杰克或吉尔等)。所以我可以按key.kind排序,但我不确定如何现在添加第二个排序条件并按它排序。如果这是SQL,它将类似于以下内容:SELECT * FROM table ORDER BY KIND,NAME; -- sort by KIND first then NAME

1 个答案:

答案 0 :(得分:2)

假设您的服务器响应存储在数组people中。然后,您可以将Array sort() method与用户定义的比较函数一起使用:

people = people.sort(function(a, b) {
    if (a.key.kind != b.key.kind) return a.key.kind > b.key.kind;
    else return a.key.name > b.key.name;
});