Sorting JSON by values

前端 未结 6 1018
北荒
北荒 2020-11-22 12:16

I have a very simple JSON object like the following:

{
   \"people\":[
      {
         \"f_name\":\"john\",
         \"l_name\":\"doe\",
         \"sequence         


        
6条回答
  •  囚心锁ツ
    2020-11-22 12:49

    Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.

    $scope.sortMyData = function (a, b)
    {
      var retVal = 0, key;
      for (var i = 0; i < $scope.sortKeys.length; i++)
      {
        if (retVal !== 0)
        {
          break;
        }
        else
        {
          key = $scope.sortKeys[i];
          if ('asc' === key.direction)
          {
            retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
          }
          else
          {
            retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
          }
        }
      }
      return retVal;
    };
    

提交回复
热议问题