Based on what I read from Does JavaScript guarantee object property order?
Object.entries()
should guarantee order.
But my project has an Angular website. On the website, I found Object.entries()
change orders every time I refresh the page.
At first 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
After 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
The object were exactly the same both time.
I can handle website has this problem, but my backend which is Firebase cloud function were written under the assumption that Object.entries()
and Object.keys()
always have the same order based on the keys.
My questions are:
- Does Firebase cloud function guarantee when the keys are same,
Object.entries()
always has the same order, and is same asObject.keys()
? - Why is it different in my Angular website?
tsconfig.json for Angular
/* To learn more about this file see: 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"
]
}
Eidt:
OK I found the problem, but still doesn't understand.
Consider following code:
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 how it supposed to be?
I directly return the object from Firestore cloud function (onCall), and I noticed the order of the key in the JSON string is different every time.