I know key order isn\'t guaranteed in JS objects, however, my data structure comes from a backend for which I have no control over. Is there anything I can do to preserve th
The JSON specification indicates that
An object is an unordered collection of zero or more name/value pairs...
Strictly speaking, the literal JSON text has an order, of course: the text isn't going to suddenly scramble itself. But your desired behavior -- an ordered set of name/value pairs -- is not a construct that JSON provides. You want an object notation to provide semantic meaning beyond the semantics that are required by the JSON specification.
In order words, doing this in JSON
{
"foo": "baz",
"bar": "egg"
}
is description of an unordered set. If you intended for this to describe an ordered set, you're not following the rules of JSON. The data happens to be ordered (because that's how character sequences work), but JSON semantics freely allow an implementation to disregard the order of name/value pairs completely when considering the data present in the input string.
You could write code that operates directly on the JSON input string, to parse the text in such a way that the input order of the keys is remembered somewhere, but a JSON parser implementation is not required to supply that functionality to you.
The correct JSON-idiomatic solution would be to provide an array of key names in the JSON response:
{
data: {
"foo": "baz",
"bar": "egg"
},
order: ["foo", "bar"]
}
Obviously, if you don't control the response, you can't do that. By choosing the represent the data in an object, the author of the response has asserted that order of keys is purely arbitrary. If the author of the JSON intends to assert order of key entries, that assertion is external to the rules of JSON.
As a practical matter, most JavaScript engines will usually choose to report key names in the order their properties were created. However, this behavior is not required by any specification (and is sometimes inconsistent in edge cases), and so could legally differ between engines and versions.