Skip to content
Advertisement

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

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…

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement