Utilize Object literal manipulation to include properties in a specific sequence

Working on a tool to generate Nassi-Shneiderman diagrams online, where each diagram is represented as an object literal with unlimited possible children.

As I aim to add a sequence into the while loop following the first sequence, I encounter the challenge of manipulating the order of an object's properties. The default inability to edit property order leads me to explore alternative solutions, such as using 3rd party libraries or restructuring my data structure entirely.

Is there a way to change the iteration order of an object's properties when looping through them? Any insights or suggestions would be appreciated.

Below is a snippet of the sample data structure/object utilized in this context:

{
    "procedure": {
        "id": "content",
        "child": {
            ...
        }
    }
}

Answer №1

(Updates in ECMAScript 2015 ("ES6"): Please refer to the latest information at the end of this response.)

The concept of object properties having no specific order applies to both JavaScript and JSON. If you require order, utilizing an array instead of object properties is necessary. To establish order, you should modify your structure to include children: [] as opposed to child: {}. Subsequently, inserting a new entry between two elements can be accomplished by employing the splice function (specification | MDN).

Regarding the ordering of object properties:

JSON

As stated on the JSON website:

An object consists of an unordered collection of name/value pairs.

(My personal emphasis)

JavaScript

In JavaScript, there are no specifications governing the sequence in which properties are accessed during a for-in loop—refer to §12.6.4 of the specification:

The process and sequence for enumerating properties (step 6.a in the initial algorithm, step 7.a in the subsequent one) remain unspecified.

(My personal emphasis)

Consequently, each JavaScript engine has the liberty to determine its behavior. It is possible that they access properties based on when they were added to the object (as seen in numerous engines), alphabetically, or depending on what is most convenient for their property storage mechanism, potentially a hash tree resulting in seemingly random ordering if the hashing method is unknown.

Similarly, Object.keys does not provide any promised order; the only assurance given in the specification is that if an engine commits to an order for for-in, then Object.keys must adhere to that same order. Yet, since the specification does not necessitate engines to guarantee an order...


With the introduction of ECMAScript 2015 (ES6), object properties now possess an order:

  1. Introduce keys as a fresh empty List.
  2. For every individual property key P belonging to O that represents an integer index, arrange them numerically in ascending order
    • Add P as the final element of keys.
  3. For all property keys P of O representing strings but not being an integer index, maintain the order of creation while listing them
    • Append P as the last item in keys.
  4. For each property key P of O representing a Symbol, follow the order of creation
    • Include P as the ultimate element in keys.
  5. Deliver keys.

...therefore, by manipulating the sequence of property additions to the object, achieving this becomes viable. Although I do not propose implementing it, this option is now feasible on compliant engines.

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

Why is the jQuery change event only firing when the page loads?

I am experiencing an issue with a .js file. The change event is only triggering when the page loads, rather than when the selection changes as expected. $(document).ready(function(){ $("#dropdown").on("change keyup", colorizeSelect()).change(); }); f ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Retrieving user information from the database and adding it to the specified element

I've been grappling with what seems like a simple question for the past hour. Below is a script that I have which pulls all active reservations from the reservations table. require("../includes/connect.php"); function dispAllReservations(){ $i= ...

Creating a bot that will only respond once when a user sends multiple photos simultaneously

I'm currently working on a Telegram bot using nodejs. I am utilizing the node-telegram-bot-api library and have implemented the on('photo') method to handle when a user sends a photo to my bot. However, I am facing an issue where if a user ...

tips for using Node Mailer to send emails without using SMTP

Currently, I am facing an issue with sending emails through nodemailer. Although I have successfully used my gmail account for this purpose in the past, I now wish to switch to using my business email to communicate with clients on a regular basis. The cu ...

Unable to reset HighCharts Speedometer value to zero

I am currently experimenting with implementing the highcharts speedometer. The goal is to simulate a connection meter - when there is a good connection, the meter should display values between 30 and 100. If the connection result from an Ajax call is any ...

Prompting Javascript Alert prior to redirection in ASP.NET

My current code is set up to display a message in an update panel while updating: string jv = "alert('Time OutAlert');"; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", jv, true); It's working well in displaying the me ...

Converting JSON data into Kotlin objects: a step-by-step guide

Having a sample of an existing JSON, my challenge lies in converting it to Kotlin. As I am relatively new to Kotlin and have been studying various tutorials, I have yet to come across examples as complex as this. Here is the JSON: { "mobile": { "id": ...

Getting a JSON response from a JSP page through an AJAX request

I'm encountering an issue with a JSP page that is supposed to send a JSON response when requested through an AJAX call. However, the response is being directed to the error part of the AJAX call instead of the success part. Below is the code in my JS ...

Refreshing an iframe located on disparate domains

There is a webpage called "main.jsp" within the domain "domain1". This page contains an iframe that loads content from another domain known as "domain2". Essentially, "main.jsp" serves as a common content platform, with the iframe displaying content from v ...

Harnessing the power of Shopify's Predictive Search API

I am currently working on implementing a custom solution using the predictive search API for when a product is out of stock. Our goal is to display an alternate product that we have chosen, rather than relying on automated recommendations. We have tagged a ...

Utilizing AngularJS to create a vertical calendar

Looking to create a vertical navigation displaying the date and day for the current week using angularjs. When clicking on the navigation div, I want an alert with the selected date to appear. I attempted this in Plunker using various templates, but was u ...

ASP.NET CodeBehind Fails to Recognize Changes in TinyMCE Textarea

I have multiple <asp:TextBox TextMode="MultiLine"> elements on a webpage. Initially, I populate them using VB code behind and then convert them into TinyMCE editors with the help of the jQuery TinyMCE plugin. Each text box has an associated button fo ...

What is the most effective way to show the current date on a webpage: utilizing JavaScript or PHP?

Looking to show the current date and time on a webpage. There are two potential methods to achieve this: (1) Using PHP, for example: <?php echo date('Y-m-d H:i:s');?> (2) ... or JavaScript, like so: <div> <script>document.wri ...

"Critical issue: Meta tags are not present on the dynamic pages of the NextJS

In my NextJS application, the pages are structured as follows: App --pages ----_app.js ----index.js ----company.js ----users ------[userID].js I have a dynamic page named [userID].js that retrieves the userID through the router to display information for ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

Why isn't the document.getElementById().value() function functioning properly within my PHP code?

When working on my PHP code, I included the following: <select class="ht__select" onchange="sorting('<?php echo $id ?>')" id="sorting"> <option value="">Default sorting</option> <option value="low_price">Sor ...

Extracting Querystring Value in C#

When using the code below to set the iframe src with JavaScript, everything works as expected. However, in the C# code behind, I am receiving the query string in a format like this: id=Y&amp%3bcust_id=100&amp%3. Is there a way to simplify this? v ...

Update the CURLOPT_URL parameter to accept user input

As someone new to coding, I have a question about using the CURLOPT_URL function in PHP. How can I input a NIK number and retrieve data from this URL: ? Any help would be appreciated, thank you! php $curl = curl_init(); curl_setopt_array($curl, [ CU ...

The function is not triggered when the select tag is changed

I'm currently working on implementing a drop-down menu using the <select> element in HTML. Here is the code snippet I have so far: <select id="Parameter1" onchange="function1()"> <option value = "0105" name = "Frequency">Frequency ...