使用JS在迭代过程中按一个字段对JSON数组排序

时间:2019-07-12 10:19:00

标签: javascript arrays sorting

我有一个如下数组:

var array = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

我想按标记字段对数组排序。我该如何实现?

更新

我使用以下函数按标记对上述数组对象进行排序。

$scope.GetSortOrder = function(prop) {  
    return function(a, b) {  
        if (a[prop] > b[prop]) {  
            return 1;  
        } else if (a[prop] < b[prop]) {  
            return -1;  
        }  
        return 0;  
    }  
};

array.sort($scope.GetSortOrder("mark"));

但随后出现以下错误

array.sort is not a function

所需的输出

  var outPut = 
  {
    "week1":[
       {"id":1,"name":"x","mark":"20"},
       {"id":2,"name":"y","mark":"30"}
    ],
    "week2":[
       {"id":3,"name":"z","mark":"10"},
       {"id":1,"name":"x","mark":"40"},
       {"id":2,"name":"y","mark":"60"}
    ]
  }

1 个答案:

答案 0 :(得分:2)

var array不是数组(它是对象),因此不能在其上使用.sort()

您似乎想对对象的进行排序。如果是这样,您想使用Object.values()来获取对象的值,循环浏览它们,然后对它们进行排序。

var obj = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

Object.values(obj).forEach(arr => arr.sort((a,b) => a.mark-b.mark));

console.log(obj);

如果您更喜欢接受属性名称的方法(例如您的示例),那么也许这种咖喱的方法对您有用。

var obj = {"week1":[{"id":1,"name":"x","mark":"20"},{"id":2,"name":"y","mark":"30"}],"week2":[{"id":1,"name":"x","mark":"40"},{"id":2,"name":"y","mark":"60"},{"id":3,"name":"z","mark":"10"}]}

const sortArrayByProperty = prop => arr => arr.sort((a,b) => a[prop].localeCompare(b[prop]));

Object.values(obj).forEach(sortArrayByProperty("mark"));

console.log(obj);