How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have.

var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"};

I am trying to populate a select element using the above json in the following way.

var selElem = $('<select>', {'name' : name, 'grp' : grp});
for(key in json1)
    selElem.append($('<option>', {value:key, text: json1 [key]}));

However, the resulting select element appears as shown below.

<select>
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="45">45</option>
    <option value="00">00</option>
</select>

The issue here is that even though "00" is the first element in the json object, it appears last in the select element.

Is there any workaround or solution available for this problem?

Answer №1

To maintain the order, it is recommended to utilize an array:

var data = [{id:"001",name:"John Doe"}, 
             {id:"002",name:"Jane Smith"}, 
             {id:"003",name:"Bob Johnson"}];

You can then iterate through the array using a loop:

var list = $('<ul>');
for(var i=0; i<data.length; i++){
    list.append($('<li>', {id:data[i].id, text: data[i].name})); 
}

For further details, refer to this jsfiddle link

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

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

The angular-block-ui feature fails to run my HTML code as a personalized message

I'm looking to enhance my UI by implementing a blocking feature with a spinner display. My attempt involved the following code: blockUI.start("<div class='dots-loader'>Minions are Working!</div>"); // code for fetching data ...

Content towering over the footer

Can anyone help me figure out how to create a footer that appears behind the content when you scroll towards the end of a website? I've tried looking for tutorials online, but haven't found exactly what I'm looking for. Most of what I'v ...

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

"Revamp the appearance of the div element upon clicking elsewhere on the

function replace( hide, show ) { document.getElementById(hide).style.display="none"; document.getElementById(show).style.display="flex"; } @import url('https://fonts.googleapis.com/css2?family=Allerta+Stenci ...

Session-based Authorization

I'm completely new to working with express.js, and I've been facing an issue while trying to create a session-cookie after logging in. Even though I can initiate the session and successfully log in, the session data doesn't carry over to the ...

Navigation menu that is vertical and includes submenus, where the parent list item remains active even when visiting subpages

I'm currently utilizing Jekyll and Compass to construct an interactive prototype. Within one of my includes, I've implemented a sidebar navigation. The challenge arises when dealing with submenu items, as the active class on the parent (li) does ...

The Chrome developer tools are unable to locate the HttpRequest

While working in Python, I am utilizing the requests library to make a POST request to a specific URL. However, upon clicking the button, it seems that nothing is happening as per Chrome Developer Tools. No XHR requests are being made and no data is being ...

What is the best way to extract JSON data that has already been double quoted in Objective-C?

Can you help me with parsing JSON data that is already double-quoted? For example, say we have received the following JSON: "first_name" = Noah; Here is the code I have tried: //"first_name" = Noah; NSString *name=[result valueForKeyPath:@"first_name"] ...

What is the process for compiled node projects to manage modifications to internal files?

I am currently developing a small program using nodejs that I intend to integrate as a backend service for an expressJS webserver that is still in the works. To prevent displaying the entire program on the webserver itself, I have learned about the possib ...

My jquery filter is not functioning properly

I need help making the active class work on each category when clicked, shifting to the next one. I've tried implementing it but no luck so far. $(document).ready(function() { $('.list-inline-item').click(function() { const value = ...

Leveraging Variables within my .env Configuration

Does anyone have suggestions on how to set variables in my environment files? Website_Base_URL=https://${websiteId}.dev.net/api In the code, I have: websiteId = 55; and I would like to use config.get('Website_Base_URL'); to retrieve the compl ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

I'm seeing a message in the console that says "Form submission canceled because the form is not connected." Any idea why this is happening?

For the life of me, I can't figure out why this code refuses to run the handleSubmit function. Essentially, the form is supposed to take an input and execute the handleSubmit function upon submission. This function then makes a POST request to an API ...

Preserving the most recent choice made in a dropdown menu

Just started with angular and facing an issue saving the select option tag - the language is saved successfully, but the select option always displays English by default even if I select Arabic. The page refreshes and goes back to English. Any assistance o ...

jQuery Live allows for the execution of functions multiple times

When utilizing jQuery's 'live' function in dynamic pages where content is loaded via Ajax, I have encountered an issue where button events detected with 'live' are being duplicated. Whenever I access the page containing these butto ...

How can JavaScript allow access to files outside of a web server environment? Could .htaccess provide a

Currently, I'm facing a challenge with my local server on Mac 10.8. I am trying to serve files such as videos and images from an external hard drive. The path for the external hard drive is HD: /Volumes/ while the web server's path is /Library/Se ...

I'm currently attempting to establish a connection between my server.js express API and MongoDB, but I keep encountering an unfamiliar error message that I'm having trouble decipher

Here is the server.js code: import express from 'express'; import bodyParser from 'body-parser'; import userRoutes from './routes/users.js'; import mongoose from 'mongoose'; co ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...

Managing active dropdown menus in VueJS

I'm having trouble figuring out why my navigation menu and method to open subitems on click are not working correctly. [![dropdown_menu][1]][1] new Vue({ el: '#app', data: { //menu "menu_title": "a", "child_ro ...