Each time the website refreshes, Object.entries() rearranges the orders

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:

  1. Can Firebase cloud function ensure that when keys are the same, Object.entries() will have a consistent order, matching that of Object.keys()?
  2. 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.

Answer №1

Is there a guarantee that Object.entries() always maintains the same order when keys are identical, like Object.keys()?

No, having a "guaranteed order" means that repeatedly calling these functions on the same object will consistently return results in the same order. However, using these functions on different objects constructed in the same way may not yield reproducible orders.

This does not ensure that you will get the same output when calling the function on various objects with similar property sets. The order depends on insertion order, resulting in potentially different arrays for objects like

{"a": 1, "b": 2, "c": 3}
compared to
{"b": 2, "a": 1, "c": 3}
. Given that your cloud function may receive diverse objects with each call, it is risky to assume anything about key order.

In any case, relying on key order would be unwise. Key-value collections lack inherent ordering, so if sequence matters, sorting the array of keys/entries is recommended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React: Oops! Looks like there's an issue - this.props.update is not defined as

Hello everyone, I'm diving into the world of programming for the first time and I might ask some silly questions along the way. Currently, I'm working on integrating a date picker into a search application built with React. The user should be ab ...

Leveraging Selenium to dismiss a browser pop-up

While scraping data from Investing.com, I encountered a pop-up on the website. Despite searching for a clickable button within the elements, I couldn't locate anything suitable. On the element page, all I could find related to the 'X' to cl ...

How to retrieve values from multiple mat-sliders that are dynamically generated using ngFor loop

Creating multiple mat-sliders dynamically in Angular looks like this: <ng-container *ngFor="let parameter of parameterValues; let i = index;"> <mat-slider (input)="onInputChange($event)" min="1" max="{{ parameter.length }}" step="1" value="1" i ...

Dealing with bulkWrites in Mongoose and MongoDB: how to handle cast errors with finesse

When importing data into my app's database using MongoDB's bulkWrite operation, I encounter a challenge. The data may contain errors as it comes from an external source. To maintain the integrity of my data, I need to update my collection while s ...

Node.js is the perfect platform for streaming videos effortlessly

I'm attempting to live stream a video from my server, but it seems like I may be doing something wrong: Here is how my routes are defined: var fs = require('fs'); router.get('/', function(req, res) { fs.readdir(__dirname + &ap ...

A guide on transforming JSON data into HTML using Rails

I'm struggling with parsing JSON on a webpage. My webpage is designed with circles, where clicking on a circle triggers a call to the controller to retrieve specific information from a database and display it as graphs and text. The issue I'm fa ...

Enhancing Bootstrap modals with dynamic content and integrating Ajax for dynamic data retrieval in Laravel

I am facing some challenges while coding in Laravel, specifically with passing data to a modal (using the Bootstrap framework) and sending data to an Ajax post request. I have an array of items with an 'id', a 'name', and 'content& ...

What is the most efficient method for linking the hostname of my website to the file path within my Express.js static file server?

When using vanilla JavaScript in the browser, we can retrieve the hostname using: window.location.hostname However, if we are working with Node.js/Express.js on the server side, how can we achieve the same result? Furthermore, I am looking for a way to ...

Implement Material UI Textfield with 'error' and 'helper text' for items within a repeated loop

I am currently working on developing an application that involves dynamic text field input using MUI textfield. This application consists of two fields - From and To. The functionality includes generating two new fields when the user clicks on the "Add New ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

How can we incorporate SaxonJS higher-order functions into the Node.js runtime, separate from JS/HTML?

We are currently in the process of transitioning an older C# system that relied on custom functions to enhance XSLT processing. Our plan is to convert it to Node.js/saxon-js. After reviewing the documentation, it appears that while higher order functions ...

Passing a variable to a modal in AngularJS

In my project, I am utilizing https://github.com/simpulton/angularjs-wizard and have made some modifications to it (specifically changed var app to $scope). It is functioning well, however, I am facing an issue where I need to pass a variable to the open f ...

How can I convert text containing in Node.js and insert actual new lines instead of the character?

I'm trying to transform a text response by removing special characters like \n and turning them into actual new lines. The initial response contains special characters -----BEGIN MESSAGE----- v1.60 hQEMAwPgeMJUXSL5Bps+U3lC8tnc D8s2Aeb7UtryIRAB ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

hide navigation on login/registration pages and display only in inner pages

My goal is to display the navigation bar only on inner pages of the application, not on the login or register pages. To achieve this, I have created a separate component for the navigation, and in the app.component.html file, I am trying to show it like t ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

Resolving the issue of multiple instances of React within a single application

I'm currently working on a React module in my local environment. To link the module, I am using npm link. Although the module is being imported successfully, the hooks inside the module are failing with the following error message: Invalid hook call ...

Error message: 'Encountered issue with react-router-V4 and the new context API in React

Currently, I am experimenting with the integration of React Router V4 alongside the new React context API. Below is the code snippet I am working with: class App extends Component { static propTypes = { router: PropTypes.func.isRequired, ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

Customize the position values of the Ngx-bootstrap Tooltip manually

I have incorporated ngx-bootstrap into my Angular 4 application. The component I am using is ngx-bootstrap Tooltip: After importing it, I am implementing it in my component's view like this: <button type="button" class="btn btn-primary" ...