Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - maintain key order when going from object -> array

Tags:

javascript

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...

like image 671
benhowdle89 Avatar asked Mar 27 '26 16:03

benhowdle89


2 Answers

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.

like image 135
dsh Avatar answered Mar 30 '26 05:03

dsh


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/


Here's how it works:

  • 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.

like image 20
merlindru Avatar answered Mar 30 '26 04:03

merlindru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!