Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object property ordering in javascript

Tags:

javascript

v8

I am trying to understand what's the thing with javascript Objects while using them as an associative array.

From ECMA:

4.3.3 An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Using them in browser (chrome):

x = { 2: 'a', 3: 'b', 1: 'c' }
> Object {1: "c", 2: "a", 3: "b"}

y = { 'b': 2, 'c': 3, 'a': 1 }
> Object {b: 2, c: 3, a: 1}

While in the first example with the numbers as keys, they became ordered, in the second example with strings, they won't ( ordered = a,b,c ).

I am using these objects with string keys and I really don't want them to change order in some stage of app(if that's even possible) because it may crash the pipeline I am using.

Question is, is this approach safe and normal for every javascript machine, or should I use other method to guarantee that order won't ever change?

Thank you!

Edit: I am using this with node.js which runs on V8 (chrome engine), which 'orders non-numerical properties in insertion order'(Felix Kling). May this behaviour of V8 change?

like image 697
petomalina Avatar asked Dec 02 '25 04:12

petomalina


1 Answers

Although Chrome may guarantee property order when using numbers as indexes in objects, the ECMA specification does not say it should do that, so by guarantee I'd not rely on this behavior. I suggest you to restructure your data to use arrays when you want to keep data order.

like image 171
Guilherme Sehn Avatar answered Dec 03 '25 17:12

Guilherme Sehn