简体   繁体   中英

angularjs disturbs json structure

I'm getting a json from server side in following order:

 [{ "outlet_id": 83 "outlet_name": "My Outlet" "address": "My Outlet" "shop_number": "123" "street": "123" "building_no": "52" "key_location": "Location 123" "mohallah": "Mohalla 123" "landline": "1235869" "owner_name": "Owner" "Manufecture": "A" "BrandName": "B" "Variant": "C" "BRANDDiscription": "D" "SIZE": "E" "Variant/Promotions": null "Segment": null }] 

but when I display it, it disturbs order, I'm using ng-repeat like:

 <td ng-repeat="(key, value) in vm.outletFieldAttrsList[0]">{{value}}</td> 

order of attributes is not same as order in JSON returned by server, anyone there who cana help?

Order of object attributes in JavaScript is not guaranteed. You need to use an Array or a Map for that.

Relevant:

AngularJS sorting by property

Javascript "objects" does not have such thing as an "order" - if you have say

{ "e": 0, "b": 123, "c": 345"...

it won't be enumerated then as e, b,c as it was set in literal - result of enumeration will be simply b, c, e ... (by alphabet).

For proper enumeration you have to store the order in some other entity (like array ["e", "b", "c"])

I think you try use arr.sort, but it is not guaranteed.

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Cherry" comes before "banana". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.

Array.prototype.sort()

I believe the best solution, It would be the response comes in the order you want.

Example:

[0: { ITEM }, 1 : {ITEM 2}]

Or create a function comparate :

items.sort(function (a, b) {
  return a.localeCompare(b);
});

More details .. , see the reference

I found solution to this problem:

 <td ng-repeat="key in objectKeys(outletFieldAttrsList[0])"> </td> 

and controller side:

 $scope.objectKeys = function (obj) { return Object.keys(obj); } 

Object.keys returns keys of that object in same sequence as they exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM