After reading the discussion on Does JavaScript guarantee object property order?
It seems that Object.entries()
should maintain order.
However, I encountered an issue with my Angular website where the order of keys in Object.entries()
changed upon refreshing the page.
Initially, the keys were:
X-MBX-ORDER-COUNT-1D
X-MBX-USED-WEIGHT-1M
X-SAPI-USED-UID-WEIGHT-1M
X-SAPI-USED-IP-WEIGHT-1M
X-MBX-ORDER-COUNT-10S
Upon refresh, the keys became:
X-MBX-USED-WEIGHT-1M
X-MBX-ORDER-COUNT-10S
X-SAPI-USED-IP-WEIGHT-1M
X-SAPI-USED-UID-WEIGHT-1M
X-MBX-ORDER-COUNT-1D
Despite the keys being identical both times.
I can manage this issue on the website, but my Firebase cloud function backend was built assuming that Object.entries()
and Object.keys()
would always follow the same key-based order.
This raises two questions:
- Can Firebase cloud function ensure that when keys are the same,
Object.entries()
will have a consistent order, matching that ofObject.keys()
? - What causes this inconsistency in my Angular site?
tsconfig.json for Angular
/* For more information about this file visit: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
"module": "es2020",
"lib": [
"es2020",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
tsconfig.json for Firebase cloud functions
{
"compilerOptions": {
"module": "commonjs",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "lib",
"sourceMap": true,
"strict": true,
"target": "es2017"
},
"compileOnSave": true,
"include": [
"src"
]
}
Edit:
Upon further investigation, I identified the problem, but remain puzzled.
Consider the following code snippet:
const x = JSON.parse('{"a": 1, "b": 2, "c": 3}')
const y = JSON.parse('{"b": 2, "a": 1, "c": 3}')
for (const k of Object.keys(x)) {
console.log(k)
}
console.log("==========")
for (const k of Object.keys(y)) {
console.log(k)
}
Result:
a
b
c
==========
b
a
c
Is this the expected behavior?
When returning objects from Firestore cloud functions (onCall), I noticed that the key order in the JSON string varies each time.