Reputation: 605
I am creating a JavaScript object as follows:
var myObjects;
for (var i = 0; i < 10; i++) {
var eachObject = {"id" : i};
myObjects.push(eachObject);
}
var message = {
"employeeDetails" : myObjects
};
After this I stringify them as follows:
JSON.stringify(message);
Does the above method always stringify the objects in the order they were in previously?
After stringification, will they be in the order 0,1,2....9 as they were previously?
Upvotes: 12
Views: 20625
Reputation: 4826
For a simple way to get top level objects (only) in a specific order from JSON.stringify()
you can use Object.keys()
with JSON.stringify
's replacer
parameter:
const str = JSON.stringify(obj, Object.keys(obj).sort());
Demo:
let obj = {
cat: 1,
a: 2,
ba: 3,
bb: 3.5,
A: 4,
'0': 5,
};
const str = JSON.stringify(obj, Object.keys(obj).sort(), 2);
const str2 = JSON.stringify(obj, null, 2);
// Output is sorted alphabetically by key name
console.log(str);
console.log('Without replacer:\n', str2);
.as-console-wrapper { max-height: 100% !important; }
The order of the keys array passed as the replacer
determines the order in the resulting string.
Note, however, as alluded to above, that using Object.keys(obj).sort()
only preserves top-level object keys, which means the stringified result will omit all nested values.
E.g. { test: { a: "I'm nested!" } }
will become {"test":{}}
.
See also:
Upvotes: 13
Reputation: 16085
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.
Upvotes: 23
Reputation: 47290
You can sort arrays using sort method.
And yes stringify retains ordering.
var cars = ["Saab", "Volvo", "BMW"];
cars.push("ferrari");
alert(JSON.stringify(cars));
cars.sort();
alert("sorted cars" + JSON.stringify(cars));
Upvotes: 5