3

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?

Dmitri Zaitsev
  • 13,548
  • 11
  • 76
  • 110
Junaid Sarwar
  • 189
  • 1
  • 13

4 Answers4

0

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

Community
  • 1
  • 1
ekuusela
  • 5,034
  • 1
  • 25
  • 43
0

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"])

0

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

calraiden
  • 1,686
  • 1
  • 27
  • 37
0

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.

Junaid Sarwar
  • 189
  • 1
  • 13