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 the key order when going from:
var obj = {
foo: 'bar',
bar: 'foo'
};
to:
Object.keys(obj); // hoping for ['foo', 'bar']
It's of the utmost importance that I keep the key order unfortunately...
No. As you wrote:
I know key order isn't guaranteed in JS objects
If you want the order you need to use an array. If you have an object, then there is no defined order to the properties.
This is doable since ES2015.
Stefan Judis explains it really well here https://www.stefanjudis.com/today-i-learned/property-order-is-predictable-in-javascript-objects-since-es2015/
Number-like keys always come first, no matter when you inserted them. They are sorted numerically.
Strings come next. They are sorted chronologically. Insert "foo" after "bar", and it'll stay that way!
Symbols come last. They are sorted chronologically, too.
const obj = { '2': null, 'foo': null, '01': null, // "01" counts as a string. Only "1" is a number-like key! 1: null, [Symbol('first')]: null };
The resulting order of those keys is "1", "2", "foo", "01", Symbol(first).
The integers were moved to the start and sorted numerically. Next are strings, in the same order as they were ("foo", then "01"). Symbols are moved to the end, but otherwise keep their order.
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