Arrangement of JavaScript objects based on timestamp key

In JavaScript, there are specific rules that dictate the order of object properties. One interesting example caught my attention.

When a timestamp in milliseconds is used as an object property key, the ordering does not function as expected.

However, if a timestamp in seconds is used as an object property key, the ordering works properly.

var objS = {
    1600333200: 'a',
    1600419600: 'b',
    1600338600: 'c'
};
console.log('seconds', JSON.stringify(objS));


var objMs = {
    1600333200000: 'a',
    1600419600000: 'b',
    1600338600000: 'c'
};
console.log('milliseconds', JSON.stringify(objMs));

Is there an explanation for this behavior?

Answer №1

Historically, the sequence of properties in an object, like a map, was typically not guaranteed. However, with the adoption of the ECMAScript 2015 Language Specification, the reliability of property order has been established. Nonetheless, the sequence of keys is still not firmly guaranteed as per the JSON guideline.

If necessary, you can create your own function to arrange the keys in numerical order.

const serialize = obj =>
  `{${Object.keys(obj)
    .sort((a, b) => parseInt(a) - parseInt(b))
    .map(key => `"${key}":${JSON.stringify(obj[key])}`).join(',')}}`;

var objMs = {
  1600338600000: 'c',
  1600333200000: 'a',
  1600419600000: 'b',
};

console.log('milliseconds', serialize(objMs));

Result

milliseconds {"1600333200000":"a","1600338600000":"c","1600419600000":"b"}

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

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

Should I install both dependencies for Moment.js Plugins?

Thinking about incorporating a moment.js plugin such as moment-business-days. Do I need to install both packages? npm install moment-business-days npm install moment // yes / no / maybe? Or is it sufficient to just install the plugin since it already inc ...

What is the module system that fabric composer utilizes for its logic JavaScript files?

I am currently in the process of creating a business-network-definition for Hyperledger using Fabric (based on generator-hyperledger-fabric). Everything has been running smoothly so far, but as we move onto our Proof of Concept (PoC), a few questions have ...

PHP Subarray Retrieval: Accessing Nested Arrays in PHP

I have a database with six columns labeled A, B, C, D, E, and X. Each unique combination of A, B, C, D, E corresponds to a different value of X. I am looking for a method to search through the database that will allow me to retrieve all values of X for va ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Which method of loading website images is quicker: sequential or parallel, utilizing Javascript?

As I work on developing an AJAX image gallery that preloads multiple large images ranging from 120kB to 2MB before the lightbox appears, a question arises: should these images be loaded sequentially (waiting for one to preload at a time) or in parallel? Wh ...

Problem related to permissions within a node.js package

Introducing my newly built npm module called emeraldfw, now available for public use. Here is a glimpse of the contents in my package.json file: { "name": "emeraldfw", "version": "0.6.0", "bin": "./emeraldfw.js", "description": "Emerald Framework ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Why does updating state lead to a re-rendering loop while setting state does not encounter the same issue?

Essentially, I have developed a REST Api that retrieves a list of components (sections) from a CMS along with their associated data. Each section in the UI is assigned a number to indicate its position, but certain sections are excluded from counting, such ...

PHP not compatible with Fancybox iframe

I'm facing a simple problem that I can't seem to figure out. I have a button that, when clicked, opens a fancybox with an iframe displaying a page from my website. This page includes a form for sending an email. Everything works fine except that ...

Using jQuery to swap out sections of a HTML tag

Similar Question: Use of jQuery for Modifying an HTML Tag? After extensive research, I have not come across a solution that fits my specific requirements. My objective is to replace a part of an HTML tag without completely replacing the entire tag. To ...

Why is it that the Json object is listed before the Json values below?

When I use org.json.simple.JSONObject to create a nested JSON object, why does the order of the JSON properties change? Desired output: { "id":"14", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="067e7e7e466 ...

Sum the properties of an array of objects by filtering them in Swift

I need help creating a shopping list based on an array of products. Within Core Data, I have an entity called "Product" which has properties for name (String) and amount (Int). Currently, I have an array of products with some duplicates, like this: var p ...

Enhancing highcharts gauge with dynamic data from JSON

I've been working hard to get my Gauge looking just right, and now I'm attempting to update it with JSON data from Thingspeak. However, when I check the page, I keep running into a ReferenceError - it says "data is not defined." If you want to t ...

What could be causing me to see a basic checkbox instead of a toggle switch in my React application?

I've been attempting to create a toggle switch that activates dark mode using Bootstrap switches, but when I save the code, it reverts back to a basic checkbox. According to the documentation, for older assistive technologies, these switch elements wi ...

Which Angular2 npm packages should I be installing?

When I'm trying to create an empty app without using angular-cli, it's really difficult for me to figure out which packages or libraries to include. Searching for angular2 on npmjs yields unwanted results, forcing me to click through multiple li ...

using ajax to fetch a file from laravel

My goal is to download a file by sending necessary parameters through an ajax request. In the process, I saved the output file in the public/exports directory and attempted to redirect to that file path in the success callback. public function downloadRe ...

Converting underscore-prefixed fields to JSON in Golang

While Go's encoding/json package is powerful for JSON marshalling, I've encountered an issue when trying to marshal data for insertion into a MongoDB instance. MongoDB recognizes _id as an indexed identifier, but the Go JSON package only works w ...

Is there a way to retrieve the size of a three.js group element?

Obtaining the dimensions of a mesh (Three.Mesh) can be done using the following code: mymesh.geometry.computeBoundingBox() var bbox = mymesh.geometry.boundingBox; var bboxWidth = bbox.max.x - bbox.min.x; var bboxHeight = bbox.max.y - bbox.min.y; var bbo ...