I am creating a javascript object as follows
var myObjects ;
for(var i = 0; i <10;i++){
var eachObject = {"id" : i};
myObjects .push(eachObject );
}
message = {
"employeeDetails" : myObjects
}
After this I stringify them as follows
JSON.stringify(message);
Does the above method stringifies the objects in the order they were previously? After stringify will they be in the order 0,1,2....9 as they were previously?
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With