如何在AngularJS的控制器中对JSON数组进行排序?

时间:2014-04-16 17:52:22

标签: javascript json angularjs

请帮助我对控制器中的以下JSON列表进行排序并在视图中显示。

实际上orderBy过滤器排序一个级别,但是我需要它递归地对子项进行排序。

输入:

R2
-->S4
------>T5
------>T4
-->S3
R1
-->S2
------>T2
------>T1
-->S1

输出:

R1
-->S1
------>T1
------>T2
-->S2
R2
-->S3
------>T4
------>T5
-->S4

请在Plunker中找到样本。

http://plnkr.co/edit/JslHwJ1CBREKf6FgYHaZ?p=preview

1 个答案:

答案 0 :(得分:1)

var sortNames = function(arr){

  arr = arr.sort(function(a,b){
    return a.name > b.name;
  })

  for (var i = 0; i < arr.length; i++){
    if (arr[i].childs){
      sortNames(arr[i].childs)
    }
  }
  return arr;
}
var names = [
    {
        "name": "Root1",
        "Id": "2f3d17cb-d9e2-4e99-882d-546767f2765d",
        "status": "",
        "dispName": "",
        "imageURL": "",
        "childCount": "",
        "childs": [
            {
                "name": "Sub1",
                "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f98f",
                "childs": [
                    {
                        "name": "Template1",
                        "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981",
                        "status": "",
                        "dispName": "",
                        "imageURL": ""
                    },
                    {
                        "name": "Template2",
                        "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f982",
                        "status": "",
                        "dispName": "",
                        "imageURL": ""
                    }
                ]
            },
            {
                "name": "Template3",
                "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981"

            }
        ]
    },
    {
        "name": "Root2",
        "Id": "ea0586e7-02cf-4359-94ba-8d9623590dfe",
        "childs": [
            {
                "name": "Sub2",
                "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c9",
                "childs": [
                    {
                        "name": "Template4",
                        "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c1"
                    },
                    {
                        "name": "Template5",
                        "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c2"
                    }
                ]
            }
        ]
    }
];

sortNames(names);