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

Puppeteer will not navigate to chrome://version when running in headless mode

Currently, I am utilizing the puppeteer.connect method to navigate to chrome://version in order to extract the user-agent being used by Puppeteer. Everything works fine when headless mode is disabled, but an error occurs when attempting it with headless mo ...

Image Animation Using a Rotational Control (HTML/JavaScript/...)

I am interested in achieving a specific effect with a series of images that transition from dark to light. My idea is to have a dial or slider underneath or over the frame so that when it is moved to the left, the black image is displayed, and when moved t ...

Guide to sending parameters to the getInitialProps function in the _app.js file within Next.js by extracting them from the URL

Shown below is the getInitialProps function for my custom MyApp. MyApp.getInitialProps = async ({ctx}) => { const { siteHeaderCollection } = await getHeaderData(ctx.query.lang) const { siteFooterCollection } = await getFooterData(ctx.query.lang) ...

Choosing an element with JavaScript

var displayedImage = document.querySelector('.displayed-img'); var thumbBar = document.querySelector('.thumb-bar'); btn = document.querySelector('button'); var overlay = document.querySelector('.overlay'); /* Itera ...

Associative TypeScript Arrays

I'm attempting to organize reservations based on business ID in order to achieve a specific end result. Here is the desired output: [ [businessID1] => [Object1,Object2, Object3], [businessID2] => [Object1,Object2], [businessID3] => [Obje ...

Obtain unique identifiers for the purpose of sorting the items

While utilizing Nuxt.js, I am fetching random images from URLs structured like this: http://www.randomimage.com?ID=myId To display 2 pictures, I use the following methods: getRandomArbitrary(min, max) { return this.numb = Math.floor(Math.random() * ...

Issue with scroll being caused by the formatting of the jQuery Knob plugin

I am currently utilizing the jQuery Knob plugin and I am looking to have the displayed value shown in pound sterling format. My goal is for it to appear as £123456. However, when I attempt to add the £ sign using the 'format' hook, it causes is ...

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...

Determine the size of an SVG while taking into consideration any strokes applied

Is there a way to seamlessly position an SVG in the corner of a div, despite having a dynamically generated stroke? Calculating the distance to the outermost part of the border proves difficult when dealing with irregular shapes like stars. Here's my ...

Removing an item from JSON data using Node.js and Express

Currently, I am attempting to remove an entry from json data. In order to view the data, I utilize the following: app.route('/data/:id') .get((req:Request, res: Response) => { let id = req.params.id; res.status(200).send(projects ...

Guide on detecting errors when parameters are not provided with req.params in Node.js

My question revolves around a piece of code that I have been working on. Here is the snippet: const express = require('express') const app = express() app.get('/test/:name', (req, res) => { const {name} = req.params; res.send(`P ...

What is preventing the random images from appearing on my browser?

Having some trouble loading random images on a page using basic JavaScript code. Following homework instructions, but the images are not showing up in the web browser. Any assistance would be greatly appreciated. Here is the code: <?xml version="1.0" ...

What is the best way to deactivate unclicked href links within a loop?

Looking at the template image, my goal is to disable all links that were not clicked when one of the links from 'number1' to 'number3' is clicked. For example, if 'number2' is clicked, then 'number1' and 'number ...

Creating a Vertical Navbar Dropdown in Bootstrap 3.0 Without Appending to the Last List Item Only

Currently, I'm in the process of creating a panel layout that features an elegant vertical navbar. Although everything seems to be aligned correctly and I've managed to implement a dropdown menu in a vertical layout, it keeps appending to the las ...

`How to implement text that changes dynamically within images using HTML and PHP`

I'm working on a PHP website with Codeigniter and I have a requirement to insert HTML text into an image fetched from a database. The content of the text will vary based on different profiles. Below is the image: The text "$40" needs to be dynamic. H ...

Implement AJAX and PHP to submit form data along with the page ID and session information

I am currently developing a school book library website project that allows students to browse and select books, as well as send requests to the librarian to borrow them. However, I am still learning jQuery and facing some challenges in handling issues. H ...

When using Express, the XML response is returning an empty document

I'm experimenting with a simple API that returns XML response: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const libxmljs = require("libxmljs"); const PO ...

Express.js automatically sets timeouts for requests to static files

I've been facing this issue for several weeks now - after launching, Express functions properly for a few hours and then suddenly stops serving static files. The situation is as follows: GET / 304 153ms GET /js/bootstrap.min.js 200 120000ms GET /img/ ...

What is the best way to simulate fetch in Redux Async Actions?

When writing tests in the Redux Writing Tests section, how does store.dispatch(actions.fetchTodos()) not trigger the fetch method when store.dispatch is directly calling actions.fetchTodos? The issue arises when trying to run similar code and encountering ...

Incorporating a pre-existing component into a Vue.JS template through an onclick event: How can this

I'm trying to enhance my template by implementing a feature that allows me to add a component simply by clicking on a button. Let me give you a glimpse of what I have in mind: The component named Draggable.vue is the one I intend to incorporate upon c ...