Arranging the data in my JSON reply

{
    "JsonResult": {
        "List": [{
            "Subject": "Something",
            "Type": 0,
            "TypeDescription": "Referral"
        }],
     }
}

When I hit my service, I receive a sample JSON response. After that, there is a button with options like

Subject, Type, and TypeDescription
.

I am looking for a way to sort the JSON Response based on the parameter I send.

function sortItems(jsonResponse, parameter){
          var sorted = jsonResponse.List.sort(function(a, b) {
          var nameA = a[parameter].toLowerCase(),
          nameB = b[parameter].toLowerCase();
          return nameA.localeCompare(nameB);
}

Although this sort function does not seem to be working properly. I already have the JSON response and need to dynamically sort it based on the provided argument.

Answer №1

function sortItems(responseData, key) {
      var sortedData =  responseData.JsonResult.List.sort(function(a, b) {
          var nameA = a[key].toLowerCase(), //note the use of brackets []
          nameB = b[key].toLowerCase(); //same applies here
          return nameA.localeCompare(nameB);
      });
}

'key', the second parameter, is a string representing the key to be searched for, and not a direct field accessor statement. Hence, it cannot be accessed from the JSON data using a dot operator.

Additionally, please ensure you use:

responseData.JsonResult.List.sort

A while ago, I faced a similar situation: Check out these helpful tips:
Stackoverflow: Sorting array of custom objects in JavaScript

Answer №2

Discover a Js Fiddle link below for an in-depth understanding:

http://jsfiddle.net/spechackers/EdAWL/

<script type="text/javascript>
        onerror = function (a, b, c) {
            alert([a, b, c]);
        };
    </script>
<script type="text/javascript>
    var x = {
        "JsonResult": {
            "List": [{
                "Subject": "Exploring J. K. Rowling's <u>Harry Potter</u> series report.",
                "Date": "Jan 25th 2009",
                "Type": "Book Report",
                "Class": "English"
            }, {
                "Subject": "Analyzing Charles Dickens' <u>Oliver Twist</u> novel report.",
                "Date": "May 1st 2003",
                "Type": "Book Report",
                "Class": "English"
            }, {
                "Subject": "Understand J. R. R. Tolkien's <u>The Lord of the Rings</u> series through this book report.",
                "Date": "Aug 7th 2007",
                "Type": "Book Report",
                "Class": "English"
            }, {
                "Subject": "Summary of the civil war.",
                "Date": "Feb 26th 2009",
                "Type": "Essay",
                "Class": "History"
            }, {
                "Subject": "Inquiry into the republican party functioning in a democracy.",
                "Date": "Apr 5th 2010",
                "Type": "Essay",
                "Class": "Government"
            }]
        }
    };
</script>
... More code snippets here...

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

What is the integration between redux and next.js like?

I am currently trying to integrate Redux into an existing Next.js project, but I am struggling to grasp how the store functions server-side. I came across this example that I am following: https://github.com/vercel/next.js/blob/canary/examples/with-redux ...

Learn how to incorporate an input field into a form using the same class name

I am facing a challenging JavaScript issue that I have been struggling to resolve. My predicament involves a dynamically formed table with form fields. Here is the code snippet in question: var table = document.getElementById("table"); var row = table. ...

Does the triple equal operator in JavaScript first compare the type of the value?

When using the triple equal operator, it not only measures the value but also the type. I am curious about the order in which it compares the value and returns false if they do not match, or vice versa. ...

Troubleshooting: My jQuery script for fading in content upon document ready is not

I'm currently working on a website where I want everything to fade in when the user enters the site. Take a look at my code: var celyLogin = $(".container"); $(document).ready(function () { /*! Fades in page on load */ $("container") ...

Accelerate Image Preloading速

I am currently in the process of creating a website that features divs with background images. Although I am new to JavaScript, I am eager to learn more about it. My main goal is to preload these images so that visitors do not encounter any delays or bla ...

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

Creating phony passwords effortlessly in JavaScript utilizing the informal library

I am trying to create a password that meets the following criteria: Minimum length: 7 Maximum length: 15 At least one uppercase letter At least one lowercase letter Special characters: ~ ! @ # $ % ^ * ( ) _ + ? I have been using the casual library for g ...

Strategies for retrieving the latest content from a CMS while utilizing getStaticProps

After fetching blog content from the CMS within getStaticProps, I noticed that updates made to the blog in the CMS are not reflected because getStaticProps only fetches data during build time. Is there a way to update the data without rebuilding? I typica ...

Receiving a response from a Node.js server using an AJAX GET request

Here's a snippet of code from app.js that retrieves an aggregated value from mongo.db. I'm attempting to use this response value on my HTML page by making an AJAX call. However, I'm facing an issue where I can't retrieve the value in my ...

How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

<tr *ngFor="let row of categories "> <td>{{row.categoryName}}</td> <td>{{row.visible}}</td> <td>{{row.instanceNumber}}</td> <td> <a class="btn btn-info btn-fill " [routerLink]="['/con ...

Experimenting with Selenium to automate processes involving dynamic class attributes

My issue involves a Button class = "searchbar__SearchButton-sc-1546roh-3 searchbar__CancelButton-sc-1546roh-4 glEceZ" I am attempting to locate this element in the browser using return browser.element('button[class^="searchbar__CancelButton-"]&ap ...

URL JSON data will not display markers

I am currently working on a map that fetches data from the police.uk API by allowing users to drag and drop a dot on the map to display crimes within a 1-mile radius. However, I'm facing an issue when trying to implement geocoding functionality by tak ...

What steps can I take to guarantee that a select change event occurs following the setting of ngmodel in Angular2?

I am facing an issue with a select element wherein a basic (change) handler is attached along with an ngmodel. Whenever an <option> with a ng value is set, the change handler triggers before the [(ngModel)] reflects the new values. <div> ...

Encountering a mysterious error while attempting to access and modify a value stored in a useState hook using the keydown

I've been attempting to create a simple animation on canvas using React.js, but I'm facing an issue with integrating my Keydown function with my useState. It seems that my useState value is not being defined properly, preventing me from changing ...

Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need. The following code is where the error occur ...

Chai-http does not execute async functions on the server during testing

In my app.js file, there is a function that I am using: let memoryCache = require('./lib/memoryCache'); memoryCache.init().then(() => { console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache())); }); app.use( ...

Learn how to update a form dynamically using the Ajax.BeginForm feature

I am currently working on updating a form within my application using Ajax.BeginForm. The update process is functioning correctly, however, upon executing the function in the controller, it redirects to a view with the controller function name displayed. ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

What is the best way to create an express route for a delayed string response that is loaded only after an API call promise is fulfilled?

app.get(`/${sumName}`, async (req, res) => { const link = `https://na1.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5?api_key=${RiotKey}` const response = await fetch(link); let data = await response.j ...