javascript - How to order by json attribute -


i have simple json file this:

{"item1": {"p1": {"p1sub1": 8, "p1sub2": 7}, "p2": {"p2sub1": 6, "p2sub2": 5} },  "item2": {"p1": {"p1sub1": 4, "p1sub2": 3}, "p2": {"p2sub1": 2, "p2sub2": 1} } } 

which retrieve this:

app.controller('customersctrl', function($scope, $http) {         $http.get("content2.json")         .success(function (data) {$scope.items = data;}); }); 

and show in html:

<ul ng-repeat="(i, val) in items | orderby:'p1.p1sub1'">     <li>{{i}} - {{val.p1.p1sub1}} - {{val.p1.p1sub2}} - {{val.p2.p2sub1}} - {{val.p2.p2sub2}}</li> </ul> 

i this, no matter put in "orderby" filter:

item1 - 8 - 7 - 6 - 5 item2 - 4 - 3 - 2 - 1 

is there way order list 'p1.p1sub1' values?

edit: want order rows p1.subp1 value has in ascendent/descendent order (in example, p1.p1sub1 8 item1 , 4 item2), instance: ascendent

item2 - 4 - 3 - 2 - 1 item1 - 8 - 7 - 6 - 5 

descendent

item1 - 8 - 7 - 6 - 5 item2 - 4 - 3 - 2 - 1 

of course small sample file. final file have many items sorted.

as @charlietfl said in comments, javascript/json objects have no property ordering. luckily json supports arrays do have inherent ordering -- indexing! arrays denoted comma-separated lists surrounded brackets, e.g. ["stringa", "stringb", "stringc"] create 3 item array containing strings in order.

since said can change json source, simplest way want split out each item own object in array:

[     {          "name": "item1",         "p1": {"p1sub1": 8, "p1sub2": 7},         "p2": {"p2sub1": 6, "p2sub2": 5},     }, {         "name": "item2",         "p1": {"p1sub1": 4, "p1sub2": 3},         "p2": {"p2sub1": 2, "p2sub2": 1},     } ] 

(if you're parsing json string, don't worry, javascript's json.parse() handles arrays without having special.)

you use ordering of array as-is, or use orderby clause similar original attempt:

<ul ng-repeat="item in items | orderby:'p1.p1sub1'">     <li>{{item.name}} - {{item.p1.p1sub1}} - {{item.p1.p1sub2}} - {{item.p2.p2sub1}} - {{item.p2.p2sub2}}</li> </ul> 

but if actual items use index-y name scheme, can drop "name" property json file , use angular's special $index property:

<ul ng-repeat="item in items | orderby:'p1.p1sub1'">     <li>{{'item' + $index}} - {{item.p1.p1sub1}} - {{item.p1.p1sub2}} - {{item.p2.p2sub1}} - {{item.p2.p2sub2}}</li> </ul> 

ascendent/descendent order can controlled prefixing 'p1.p1sub1' in orderby either '+' or '-', e.g. orderby:'-p1.p1sub1' descending order.


Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -