Does JSON.stringify preserves order of objects in array

后端 未结 3 585
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 13:27

I am creating a javascript object as follows

var myObjects ; 
for(var i = 0; i <10;i++){
    var eachObject = {\"id\" : i};
    myObjects .push(eachObject         


        
相关标签:
3条回答
  • 2020-12-06 13:58

    There is nothing in the docs that explicitly confirms that the order of array items is preserved. However, the docs state that for non-array properties, order is not guaranteed:

    Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

    Even if the order of array items would be preserved, I would not count on this but rather sort the items myself. After all, there will most likely be some business or presentation logic that indicates how the items should be sorted.

    0 讨论(0)
  • 2020-12-06 14:12

    For a simple way to get top level objects in a specific order from JSON.stringify() you can use:

    const str = JSON.stringify(obj, Object.keys(obj).sort());
    

    The order of the keys [] passed as the replacer determines the order in the resulting string.

    See: https://dev.to/sidvishnoi/comment/gp71 and "sort object properties and JSON.stringify" - https://www.tfzx.net/article/499097.html

    Another more rigorous approach is: https://github.com/develohpanda/json-order

    And:https://www.npmjs.com/package/fast-json-stable-stringify will output in key order. You can also use your own sort order function.

    I found this after lots of Google'ing.

    0 讨论(0)
  • 2020-12-06 14:13

    You can sort arrays using sort method.

    And yes stringify retains ordering.

    jsfiddle

    var cars = ["Saab", "Volvo", "BMW"];
    cars.push("ferrari");
    alert(JSON.stringify(cars));
    cars.sort();
    alert("sorted cars" + JSON.stringify(cars));
    
    0 讨论(0)
提交回复
热议问题