如何基于具有不同排序顺序的多个值对json对象进行排序

时间:2015-02-20 09:24:51

标签: javascript jquery json sorting

我有以下JSON对象

   var data1 =  [
    {id: "1", name: "b", lastname: "y", marks: "10"},
    {id: "1", name: "a", lastname: "x", marks: "20"},
    {id: "2", name: "a", lastname: "x", marks: "30"},
    {id: "2", name: "b", lastname: "x", marks: "40"},
    {id: "2", name: "c", lastname: "z", marks: "60"},
    {id: "3", name: "d", lastname: "x", marks: "50"},
    {id: "3", name: "a", lastname: "c", marks: "70"}    
  ];

我根据不同的条件对此对象进行排序,例如 -

首先按asc顺序按名称排序

而不是按照desc顺序对姓氏进行排序

比按desc顺序的标记排序rsult

字段及其订单类型由网页动态生成。

***这里排序类型和theire类型没有修复它可能是名称asc,标记asc,lastname desc或标记desc,lastname desc,name asc

任何人都可以帮我建议任何jquery,java脚本插件或函数吗?

1 个答案:

答案 0 :(得分:1)

如果您实现自己的自定义排序功能,则可以使用sort来实现此目的。像这样:

function sortFunc(a, b) {
    if (a.name < b.name)  return -1;
    else if (a.name > b.name)  return 1;
    else {
        if (a.lastname < b.lastname)  return 1;
        else if (a.lastname > b.lastname)  return -1;
        else {
            if (a.marks < b.marks) return 1;
            else if (a.marks > b.marks) return -1;
        }
        return 0;
    }
}

console.log(data1.sort(sortFunc));

Example fiddle