Tejaswi katha
Tejaswi katha

Reputation: 39

Can the Order of the array elements changed after Object.values() is used on the object?

I have an object like this :

object = {
  1483295400000: {label: "Jan 02 to 08", total: 8062, billings: Array(4)},
  1483900200000: {label: "Jan 09 to 15", total: 9940, billings: Array(8)},
  1484505000000: {label: "Jan 16 to 22", total: 7901, billings: Array(5)},
  1485109800000: {label: "Jan 23 to 29", total: 4652, billings: Array(3)},
  1485714600000: {label: "Jan 30 to 05", total: 3952, billings: Array(2)}
}

When I used Object.values(object) I got an array like this :

[
  { label: "Jan 23 to 29", total: 4652, billings: Array(3) },
  { label: "Jan 16 to 22", total: 7901, billings: Array(5) },
  { label: "Jan 02 to 08", total: 8062, billings: Array(4) },
  { label: "Jan 09 to 15", total: 9940, billings: Array(8) },
  { label: "Jan 30 to 05", total: 3952, billings: Array(2) }
]

Why the order of the objects in the array changed and what is the reason?

Upvotes: 2

Views: 72

Answers (1)

Ori Drori
Ori Drori

Reputation: 192317

According to Dr. Axel Rauschmayer's article - The traversal order of object properties in ES6, the order of travesral is:

  • First, the keys that are integer indices (what these are is explained later), in ascending numeric order.
  • Then, all other string keys, in the order in which they were added to the object.
  • Lastly, all symbol keys, in the order in which they were added to the object.

Demo:

const obj = { b: 'key1', 3: 'c', 1: 'a', 2: 'b', a: 'key2' };

console.log(Object.values(obj)); // a, b, c - values of numerical keys, key1 and key2 - string keys in order of appearance in original object

Upvotes: 3

Related Questions