MTK MTK - 3 months ago 34
Javascript Question

Show original order of object properties in console.log

I need for some debugging to see the original order of one JavaScript object's properties but (at least in chrome devtools)

console.log()
shows me an alphabetically ordered object.

Ex:

var obj = {
z: 1,
t: 2,
y: 3,
a: 4,
n: 5,
k: 6
}


console.log(obj)
shows this:

Object {z: 1, t: 2, y: 3, a: 4, n: 5…}
a:4
k:6
n:5
t:2
y:3
z:1

//expected (needed ) original order
z: 1
t: 2
y: 3
a: 4
n: 5
k: 6

Answer

console.log does indeed sort the properties, in some cases you can use JSON.stringify which preserves the order, e.g.

console.log(JSON.stringify(obj, 0, 4))

NB: contrary to the popular belief, js objects maintain the enumeration order, as per the OwnPropertyKeys specification (integers first, then other properties in insertion order)