The order of the LinkedHashMap returned from the server is not maintained in the AJAX response

I have implemented a LinkedHashMap to store map entries sorted by a specific business rule, and then sending it to the client. However, I am facing an issue where my AJAX response is always sorted by the map key instead of the business rule.

Here is the code for my sorting function:

protected Map<Long, String> sortWarehousesMap(Map<Long, String> warehousesMapTemp) {
    List<Map.Entry<Long, String>> entries = new ArrayList<Map.Entry<Long, String>>(warehousesMapTemp.entrySet());

    Collections.sort(entries, new Comparator<Map.Entry<Long, String>>() {

        public int compare(Map.Entry<Long, String> a, Map.Entry<Long, String> b) {
            return a.getValue().compareTo(b.getValue());
        }
    });

    Map<Long, String> sortedWarehousesMapTemp = new LinkedHashMap<Long, String>();
    for (Map.Entry<Long, String> entry : entries) {
        sortedWarehousesMapTemp.put(entry.getKey(), entry.getValue());
    }
    return sortedWarehousesMapTemp;
}

I would appreciate any help or insights into what may be causing the issue in my code.

Answer №1

Encountered a similar issue that wasn't present while using Firefox.
The problem arises when the returned map is mistakenly identified as an array.
The key in your map is a Long data type (similar to using a String with an integer value, like "5" for instance), resulting in an array.
My workaround involved adding an underscore "_" before the key to create a placeholder key.

Answer №2

It seems like you are dealing with an AJAX response, which suggests that the data is being converted into a JSON format at some point. Since you are utilizing a Map, the data will be transformed into a JSON object. Unfortunately, the JSON specification does not specify the order of properties in an object (refer to Does JavaScript Guarantee Object Property Order?), as it is not defined. The library you are using to convert Java objects to JSON representation is likely sorting the keys for you.

If maintaining the order of elements in JSON is essential, you will need to utilize a JSON array instead.

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

When using Jquery, input can be appended on the last child element when a key

I am new to JavaScript and want to enhance my page's functionality using jQuery. Here is my current HTML: <div class="input_fields_wrap"> <div><ul class="inputList"></ul></div> </div> My goal ...

What is causing my React Query query function to be activated even though it is supposed to be disabled?

My goal is to dynamically set parameters and select a fetching function within a React Query function (useSpeciesCodes.js). The decision of which API endpoint to fetch from (using either getSpeciesCodesByRegion or getSpeciesCodesByAddress) should be based ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

Utilizing Salesforce and DocuSign: A guide to automatically filling in the recipient of my envelope through DocuSign with the contacts from my records

In my Salesforce work, I'm currently customizing the Quote object. The default button labeled "Send with DocuSign" is already included on the Quote layout. My goal is to automatically populate the recipient of the DocuSign envelope with the contact(s) ...

How to Choose a Radio Button from a Group using Selenium WebDriver and Java

My goal is to be able to choose a specific radio button from a set of radio buttons grouped by the name attribute: <div> <input type="radio" name="exampleInputRadio" id="optionRadio1" value="1"> <input type="radio" name="exampleInpu ...

How can I retrieve text instead of HTML using jQuery.get?

I'm facing an issue where I am trying to retrieve data from another site using the code below: jQuery.ajaxSetup({ crossDomain: true, dataType: "jsonp text" }); jQuery.get(url, function(rawContent) { console.log(rawContent); }); However, ...

Challenges with Vue and the <noscript> element

I recently deployed a vue app and everything seems to be functioning as expected. However, I encountered an issue when trying to view the page source in any browser - the actual content is not visible and instead, the body section starts with a message ins ...

Having trouble with linking an external JavaScript file inside the head tag?

I've connected my script.js file to my index.html file, and both files are located in the same directory. I initially linked the script.js file in the <head> section, but it wasn't working as expected. Upon checking the console, I encounter ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

Is it possible to remove a specific directory from the webpack build configuration in a vue-cli-3 setup?

After spending 3 hours adding the line: exclude: ['./src/assets/sass'] in 20 different places, I am seeking guidance on where it should actually be placed. Below is my current setup for the css-loader (util.js): 'use strict' const path ...

Upgrading to Angular 2: Utilizing ElementRef in ES5

Currently, I am facing a challenge in creating an Attribute directive for Angular 2 that would allow me to set multiple default HTML attributes using a single custom attribute. My intention is to apply this directive specifically to the input element. Howe ...

Is it possible to utilize window.location.replace function within an iframe?

Is it possible to use window.location.replace to bypass history and target on-page anchors without page reloads, but encounter issues when working within iframes? The main problem seems to be a CSP (content security policy) violation for script-src ' ...

Adding real-time value to AngularJS directives without triggering reassessment

Seeking guidance on utilizing an AngularJS directive as an HTML element, with the intention to provide it two values. One will be fetched by iterating through a collection, while the other will be derived from that value: <mydirective myval="val" mymag ...

What is the best way to load my CSS file using express.static?

How do I properly load my CSS file using express.static in Node.js? I have attempted various methods to link my stylesheet to my HTML file through Express, and I'm also interested in learning how to include images, JavaScript, and other assets to crea ...

Next.js example encounters JSON parsing issues with Transformer.js model

While using Brave browser Version 1.61.101 Chromium: 120.0.6099.71 (Official Build) (x86_64) (and also on Chrome Version 120.0.6099.62 (Official Build) (x86_64) without encountering any errors), I faced a JSON parsing issue when attempting to run the clien ...

Experiencing a "404 Page Not Found" error while making an Ajax request in ASP.NET MVC

An error occurred on the server which caused the resource to not be found. The requested URL may have been removed, changed, or temporarily unavailable. Please double check the URL for accuracy. Requested URL: /Contact/PopBid Error in Controller: [H ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Exceeded Limit: Google Maps API cannot process more than 10 destinations at this time

After spending the entire day researching, I am still unable to find a solution that solves my issue. I am utilizing the Google Maps Distance Matrix Service with 1 origin and 14 destinations. While testing the modified sample code from Google (https://deve ...

What is the best way to implement a string method in the MVC5 controller via Ajax without causing the view to refresh?

Hello there. I am seeking some assistance with a void deletephoto method in my productmasters controller. Here is the code snippet for that method: [HttpPost] [ValidateAntiForgeryToken] public void DeletePhoto(ProductMaster productMaster,strin ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...