-2

For example the following

[
    {'1000': '', '5000': '', '10000': '', 'Name': 'test1', 'Email': 'test1@gmail.com', 'Reason': ''},
    {'1000': '', '5000': '', '10000': '', 'Name': 'test2', 'Email': 'test2@gmail.com', 'Reason': ''}
]

Is there a way to reorder like:

[
    {'Name': 'test1', 'Email': 'test1@gmail.com', '1000': '', '5000': '', '10000': '', 'Reason': ''},
    {'Name': 'test2', 'Email': 'test2@gmail.com', '1000': '', '5000': '', '10000': '', 'Reason': ''}
]
Min Min
  • 125
  • 1
  • 10

2 Answers2

0

In your specific case, the answer is no. Although ES6 (along with modern browser standards and implementations) guarantee the order of object properties, there's one major exception: integer indices.

Due to your object having keys like '1000', '5000', and '10000', you won't be able to achieve the order you desire; these integer indices will always be first.

Property keys are traversed in the following order:

  • First, the keys that are integer indices in ascending numeric order.
  • Then, all other string keys, in the order in which they were added to the object.

[...]

Roughly, an integer index is a string that, if converted to a 53-bit non-negative integer and back is the same value. Therefore:

  • '10' and '2' are integer indices.
  • '02' is not an integer index. Coverting it to an integer and back results in the different string '2'.
  • '3.141' is not an integer index, because 3.141 is not an integer.

(Source)

And a brief example:

const obj = {
  "Z": 1,
  "B": 2,
  "C": 3
};

console.log(obj);   //Maintains creation order

const obj2 = {
  "A": 1,
  "B": 2,
  "100": 3
}

console.log(obj2);  //Does not maintain creation order
Community
  • 1
  • 1
Tyler Roper
  • 20,529
  • 6
  • 30
  • 51
0

The order of object properties should not matter. If it does you have a bad design at hand. The best approach is to rethink your design.

stormpat
  • 5,099
  • 3
  • 23
  • 29