An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string with the client's name)?

I have attempted the following code but it retrieves all the data:

for (var i = 0; i < json.length; i++) {
    $.data = (json[i].klID = "@Html.DisplayFor(model => model.klient)");
    var dateString = json[i].datum.substr(6);
    var currentTime = new Date(parseInt(dateString));
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var date = day + "/" + month + "/" + year;

    tr = $('<tr/>');
    tr.append("<td>" + json[i].pID + "</td>");
    tr.append("<td id='date'>" + date + "</td>");
    tr.append("<td>" + json[i].description + "</td>");
    tr.append("<td>" + json[i].popust + "</td>");
    $('table').append(tr);

Please help me. Thank you.

Answer №1

The code provided does not seem to be relevant to your issue as there is no filter mentioned here. If you only want to display items where kIID equals 'client', you can use the following if condition:

if(json[i].klID === 'What ever name'){
    var dateString = json[i].datum.substr(6);
    var currentTime = new Date(parseInt(dateString));
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var date = day + "/" + month + "/" + year;

    tr = $('<tr/>');
    tr.append("<td>" + json[i].pID + "</td>");
    tr.append("<td id='date'>" + date + "</td>");
    tr.append("<td>" + json[i].description + "</td>");
    tr.append("<td>" + json[i].popust + "</td>");
    $('table').append(tr);
}

Answer №2

ES6 introduces a powerful filtering method:

let data = ['apple', 5, 'banana', 8, 9];
let result = data.filter((item) => (
  isNaN(parseInt(item))
);
console.log(result); // displays: ['apple', 'banana']

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

Double Serialization with Java's Jackson Library

In my code, I have a class that includes a String field and a Map field. My goal is to serialize this class into JSON using Jackson. public class Mapping private String mAttribute; @JsonIgnore private Map<String, String> mMap; @J ...

Streamline uploading files with AngularJS using Selenium

I am utilizing Powershell to operate .NET Selenium with a FirefoxDriver in order to automate certain tasks. One of these tasks involves file uploads, and the website I am working with appears to have been built using AngularJS. After some experimentation, ...

Transforming an Axios image stream into a string by encoding it with Base64?

Currently, this is what I have in place: const Fs = require('fs') const Path = require('path') const Axios = require('axios') var {Base64Encode} = require('base64-stream'); const url = 'https://unsplash.co ...

Unable to run the JSON.parse() function while using the 1.10.2 version of jquery.min.js

Has anyone else encountered a situation where using JSON.parse() to parse the PHP array return only works when applying 1.3.2/jquery.min.js and not 1.10.2/jquery.min.js? If so, what solution did you find? PHP array return $returnArray['vercode' ...

Verifying the visibility of an element

I am facing a challenge with a list of apps displayed on a non-angular page. The availability of these apps depends on the subscription level purchased by the user. Even if an app has not been purchased, it is still listed but displayed with an overlay (pl ...

Jade fails to show image in route with parameter

Currently, I am utilizing express 4 and have images saved in the uploads directory. This is a snippet of my code: app.use(express.static(__dirname + '/uploads')); //This part works app.route('/') .get(function (req, res) { ...

I am looking to split an array into smaller subarrays, each containing 5 elements, and assign a distinct class to the elements within each subarray. How can I

I have a group of "n" "li" elements that I would like to split into "x" subsets using jQuery. Each subset should contain 5 "li" elements, and I also want to assign a different class to each subset. <ul> <li>text1</li> <li>text2&l ...

Is it possible to send an email with an attachment that was generated as a blob within the browser?

Is there a way to attach a file created in the browser as a blob to an email, similar to embedding its direct path in the url for a local file? The file is generated as part of some javascript code that I am running. Thank you in advance! ...

Failure to process JsonWebTokenError due to a corrupted signature in the middleware

I am facing an issue with my middleware when the jwt.verify(request.token, process.env.SECRET) function raises a JsonWebTokenError: invalid signature with middleware error upon receiving an invalid token. Despite configuring my middleware correctly, this e ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

Firebase web authentication is most effective upon the second attempt

I am currently working on a website that interacts with Google's firebase to read and write data. The website has both anonymous and email authentication enabled. Users can view the data anonymously, but in order to edit or write new data, they must s ...

Using Ajax to dynamically generate column headers in Datatables

Is there a way to create a header title from an ajax file? I've been trying my best with the following code: $('#btntrack').on('click', function() { var KPNo = $('#KPNo').val(); var dataString = & ...

Finding numerous keywords in a given text (Javascript)

Here is the code snippet I'm working with: // Finding multiple keywords within a text // Scenario 1 var inputText = "Hello, My name is @Steve, I love @Bill, happy new year!"; var terms = ["steve"]; var result = inputText.toLowerCase().search([terms]) ...

Retrieve the highest value from a JSON array in Excel VBA using a non-iterative method

Extracting the highest value of "id" from a JSON data string without iterating can be challenging. The given JSON data string is as follows: "ball_coordinates": [ { "id": 3938706, ...

"Identify the protocol name (string) based on a specific port number in TCP/UDP communication

Is there a built-in function in any web-oriented language to return protocol names based on port numbers? For example, if we have the following code: protocol = get_protocol_name(22) print protocol We would expect it to print out "ssh". A more detailed ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

Loading Images in Advance with jQuery, Native JavaScript, and CSS

After successfully implementing a method to hover on a small image and load an additional image to the right side of the page, I am now looking to enhance user experience by preloading images. Is there a way to preload an image using JQuery, allowing it t ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

Vanilla JavaScript MVC - Send notification to controller from model upon successful AJAX completion

I am facing some challenges with my first vanilla JS MVC app. When my model sends an AJAX request to the server, the controller updates the view before waiting for the promise to resolve, resulting in an empty update on the view. How can I inform the contr ...

JavaScript Array Problem

Could you please review the code below and help me understand why I am encountering issues when trying to run the program? $(document).ready(function() { var comp = new Array("AAPL", "MSFT", "XRTX&"); var t = setInterval(function(){ ...