How to change the order of the fields in JSON

后端 未结 6 911
孤城傲影
孤城傲影 2020-12-01 17:13

Scenario: Consider I have a JSON documents as follows:

   {
     \"name\": \"David\",
     \"age\" : 78,
     \"NoOfVisits\" : 4
   }
         


        
6条回答
  •  心在旅途
    2020-12-01 17:44

    Objects have no specific order.


    Update:

    ES3 Specs

    An ECMAScript object is an unordered collection of properties

    ES5 Specs

    The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

    Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.


    However. If you want to rely on the V8 implementations order.

    Keep this in your mind.

    When iterating over an Object, V8 iterates as followed

    1. Numeric properties in ascending order. (Though not guaranteed)
    2. Non-numeric properties in order of insertion.

    Shown in following example

    var a = {c:0,1:0,0:0};
    
    a.b = 0;
    a[3] = 0;
    a[2] = 0;
    
    for(var p in a) { console.log(p)};
    

    gives the output

    1. 0
    2. 1
    3. 2
    4. 3
    5. b
    6. c

    If you want guarantee order ...

    you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

    (MDN)

提交回复
热议问题