Switching a ForEach from JQuery to Vanilla Javascript

I am currently in the process of eliminating the Jquery dependency from a project and reworking some code.

 var request = new XMLHttpRequest();
request.open('GET', 'data.php', true);

request.onload = function() {
if (this.status >= 200 && this.status < 400) {
    // Success!
    var data = JSON.parse(this.response);
    if(!Object.keys(data).length) {
        document.getElementById('MOStatus').innerHTML = 'No';
    }
    else {
        document.getElementById('MOStatus').innerHTML = data.length;
    $redwarnings = 0;
        $amberwarnings = 0;
        $yellowwarnings = 0;
    for (var warningLevel in data) {
        switch(data[warningLevel]) {
            case "yellow":
                    $yellowwarnings++;
                warningColor = '#FFE923';
            break;
            case "amber":
                    $amberwarnings++;
                    warningColor = '#ff9900';
            break;
            case "red":
                    $redwarnings++;
                    warningColor = '#cc0033';
            break;
            default:
            break;
        }
    }

    } //Closes the else that comes into play if array is not empty.


} else {
    // We reached our target server, but it returned an error

}
};

request.onerror = function() {
// There was a connection error of some sort
};

request.send();

Despite correctly calculating the length of the data, my revised code does not seem to efficiently loop through and tally the red, yellow, and amber warnings.

I believe the issue lies in how I am referencing keys/values within JavaScript - unlike the JQuery-dependent code where this.warningLevel functions as intended, it does not operate properly in the non-JQuery version.

Answer №1

data consists of an array of objects, meaning data[warningLevel] will result in an object: switching over it won't provide the colors you seek. Begin by extracting the property from the object:

for (const { warningLevel } of data) {
  switch(warningLevel) {
    // add the remaining cases for your switch code
  }
}

Alternatively, a more concise approach would be to utilize an object with key-value pairs representing the colors instead of individual variables:

const warnings = {
  yellow: 0,
  amber: 0,
  red: 0
};
for (const { warningLevel } of data) {
  warnings[warningLevel]++;
}

You can then refer to warnings.yellow, warnings.amber, and

warnings.red</code instead of separate variables like <code>$amberwarnings
.

(since it seems that warningColor is not used, you can remove it)

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

I'm experiencing an "existing database with different casing already exists" error, even though I have no intention of creating a new database

My goal is to include a new word in a database called "wordsDb" within a collection named "wordsCollection": dbName = "wordsDb"; collectionName = "wordsCollection"; connectionUri = //... (secret) async add(word) { try { ...

What is a suitable alternative to forkJoin for executing parallel requests that can still complete even if one of them fails?

Is there a more robust method than forkJoin to run multiple requests in parallel and handle failed subscriptions without cancelling the rest? I need a solution that allows all requests to complete even if one fails. Here's a scenario: const posts = th ...

Gather numerical values and transform them into dates using AngularJS

My Angularjs project involves 3 scopes for year, month, and day which are retrieved from 3 input boxes. I need to combine them into a date, but the current code inserts the date with an additional 22:00:00 like 2019-06-01 22:00:00.000. How can I insert the ...

What is the best way to conceal elements that do not have any subsequent elements with a specific class?

Here is the HTML code I have, and I am looking to use jQuery to hide all lsHeader elements that do not have any subsequent elements with the class 'contact'. <div id="B" class="lsHeader">B</div> <div id="contact_1" class="contac ...

I am able to access the JSON file from the URL without any issues, but for some reason, I am unable to fetch it using $

(function(){ $(document).ready(function(){ $.getJSON('http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=AAPL&callback=?', function(){console.log("function was run");}); }); }()) I recently delved into working with APIs. Ho ...

Finding specific data within a nested HTML name array using either JQuery or JavaScript based on the second level key

Is there a way to target all input elements with names that contain 'pref[*][location][]' using a jQuery selector or JavaScript? Specifically, I want to retrieve those inputs based on the 'location' key in the second level. <input ty ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

Creating a flexible grid layout that adjusts to show either one or two columns on smaller mobile screens

NOTE: This is not a duplicate as the layout order for columns and rows is specifically tailored for mobile devices. I am attempting to showcase this grid design on mobile devices with the following sequence: First row: header (1 column, full width) Secon ...

What is the method to generate a list where every item is a list within AngularJS?

Is it possible to create a nested list in AngularJS 1.3 where each option contains its own list? I've tried implementing it using this, but the select tag seems to cut it short. Any solutions or workarounds for this issue? <body ng-app=""> &l ...

How to verify the presence of a file in the Meteor public directory

This code snippet in the Meteor client is experiencing issues when trying to determine the existence of a file located in the app/public directory. When executed in the browser console using the following commands, it returns undefined: utility.isFileExis ...

State of loading getServerSideProps in Next.js

Can we implement a loading state similar to when retrieving data on the client-side? I'm interested in having a loading state, maybe with a loading-skeleton like react-loading-skeleton On the client-side, we can achieve this by: import useSWR from & ...

Angular allows you to set specific conditions for when a failed HTTP request should be retried, and you can also specify the number of attempts that should be

Within my angular application, I have a post request that needs to be retried based on the error message, but with a limit on the number of attempts. Initially, I attempted the following approach: public post(url, data) { this._http.post(url, data).pi ...

The duplication of the Javascript code is creating a conflict within the slider functionality

Attempting to create both an image slider and text slider on the same page using the same JavaScript is proving to be a challenge. Despite researching and trying to implement a no-conflict solution, the sliders still do not function properly together. Wh ...

Struggling to make the javascript function compatible with the drop-down menu

I'm encountering issues with making my JavaScript work properly alongside my HTML. Specifically, I want the "activity" drop-down box to function in conjunction with the "city" drop-down box. For instance, if I choose "Brisbane" and then select an acti ...

A guide to updating property values in an array of objects in JavaScript while ensuring they remain in consecutive order

I am dealing with an array of objects called list. The parameters rid and rorder are provided for processing. -> 1. Whenever the value of rid matches the id in the list, the itemorder is updated with the value of rorder. -> 2. In the updated list p ...

Leveraging a script within a React component

Trying to implement a payment modal using a js script has led me to suspect that mounting it on the root div causes all components to unmount. I am looking for a way to conditionally load the modal so that users can cancel and open it later. const load ...

Retrieve a specific quantity of items from an array

I recently started using Postman to develop some test cases. Many of the responses I receive with the get method contain large arrays with numerous objects (I have simplified them here for readability, but each object actually has over 20 properties). Cu ...

Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, ed ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

Error: The provided content type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported in this context

I am currently attempting to create a post using JavaScript with AJAX to communicate with a Spring controller $("#crear").click(function () { var user = document.getElementById("user").value; var client = document.g ...