Managing several items within one function

I am working with a json file that contains similar data sets but different objects.

{
    "AP": [{
            "name": "Autogen Program"
        }, {
            "status": "Completed"
        }, {
            "start": "2014-05-05"
        }, {
            "end": "2014-05-05"
        }],
    "BP": [{
            "name": "Backend Program"
        }, {
            "status": "In Progress"
        }, {
            "start": "2014-05-05"
        }, {
            "end": ""
        }],
    "AP": [{
            "name": "Capital Program"
        }, {
            "status": "Pending"
        }, {
            "start": ""
        }, {
            "end": ""
    }]
}

I have developed a function to individually call each object.

$(function() {
    $.getJSON('http://localhost:8080/GChartServlet/data1.json', function(statusDataSet) {
        $.each(statusDataSet.AP, function(i, f) {
            var color;
            switch(f.status) {
                case "In Progress":
                    color = "yellow";
                    break;
                case "Pending": 
                    color = "red";
                    break;
                case "Completed": 
                    color = "green";
                    break;
            }

            $("#stat1").append(f.value).css('background-color', color);
        });
    });
});

I am wondering if it is possible to retrieve all the status values using a single function. Or, how can I separate the color case logic into a separate function in order to avoid repeating the switch statement for each function?

Maybe something like this:

$("#stat1").append(AP.status).css('background-color', color);
$("#stat2").append(BP.status).css('background-color', color);

Answer №1

To embrace the principles of DRY (Don't Repeat Yourself), consider implementing a versatile wrapper function that can handle various types by passing arguments to specify the type to process and the element to append to.

Instead of using a switch statement, opt for a simple object mapper as the logic remains consistent across all cases, making a switch statement unnecessary.

function myFunction(type, elementToAppend){
    $.getJSON('http://localhost:8080/GChartServlet/data1.json', function(dataSet) {
        $.each(dataSet[type], function(i, item) {
            var colorMap = {
                "In Progress" : "yellow",
                "Pending"     : "red",
                "Completed"   : "green"
            };

            elementToAppend.append(
                $('<span />', { text : item.value })
                    .css('background-color', colorMap[item.status]);
            );
    });
}

Usage:

myFunction('AP', $('#stat1'));
myFunction('BP', $('#stat2'));

Answer №2

A potential solution could be creating a function as follows:

function getColorBasedOnStatus(status) {
  let color;
  
  switch(status) {
    case "In Progress":
      color = "yellow";
      break;
      
    case "Pending":
      color = "red";
      break;
      
    case "Completed":
      color = "green";
      break;
  }
  
  return color;
}

Answer №3

Below is a code snippet that can help you achieve your goal:

 var colorMap = {"In Progress": "yellow", "Pending": "red", "Completed": "green"};
 $("#taskStatus").append(task.status).css('background-color', colorMap[task.status]);

If you want to loop through all tasks, you can use the following approach:

 var statusColorMap = {"In Progress": "yellow", "Pending": "red", "Completed": "green"};
 $.getJSON('http://localhost:8080/TaskData/tasks.json', function(tasks) {
    $.each(tasks.tasksList, function(index, task) {
        if (task.status != undefined) {     
             $("#taskList").append(task.status).css('background-color', statusColorMap[task.status]);
        }
    });
  });

Feel free to reach out if you need any clarification or encounter any issues with the implementation.



I also recommend structuring your data in the format below for better readability and easier processing:

{
"task1": {
        "name": "Project Alpha",
        "status": "Completed",
        "start_date": "2022-01-01",
        "end_date": "2022-01-31"
    },
"task2": {
        "name": "Project Beta",
        "status": "In Progress",
        "start_date": "2022-02-01",
        "end_date": ""
    }
}

If you switch to this format, the function can be modified as shown below:

 var colors = {"In Progress": "yellow", "Pending": "red", "Completed": "green"};
 $(function() {
  $.getJSON('http://localhost:8080/TaskData/tasks.json', function(data) {
    $("#taskList").append(data.task1.status).css('background-color', colors[data.task1.status]);
  });
});

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

Using jQuery's .html function to insert images

I have a unique counter that counts in currencies, such as Yen and Euro. Each number, as well as the currency sign and separator, are all displayed on the webpage using custom-designed icons. I utilize the display: flex; property in my container div and ap ...

Are the commands overlapping?

Currently, I am in the process of developing a dynamic discord chat bot using JavaScript and node.js. One of my goals is to implement a specific command without interfering with an existing one. The bot functions flawlessly across all servers where it is ...

Avoiding node_modules in Webpack 2 with babel-loader

After updating to Webpack 2, I've run into an issue with the "exclude" property in my "rules". It seems I can no longer pass "exclude" into "options". What is the correct approach to handling this now? Previously: { test: /\.js$/, loader: ...

Converting JSON to a std::string in C++ retrieved from a URL

Is there a simple method to fetch JSON data from a URL link and convert it into a std::string in a C++ file? I'm looking to implement this functionality and would appreciate any guidance or advice on how to achieve this. ...

Issue with querying and ordering products in Django using Python when passing values through the GET request

I have been working on a project where I need to filter products and sort them by price in ascending and descending order. Here is the code snippet from my view: def is_valid_queryparam(param): return param != '' and param is not None def f ...

Encountering a BAD REQUEST error while attempting to access the Okta API from a C# MVC application

I have been experimenting with creating a sample application using the Okta platform to generate users. Despite making API calls, I consistently encounter a "BAD REQUEST" response when running my C# MVC application on Visual Studio 2013 update 5 towards my ...

Performing an XMLHttpRequest to Submit an HTML Form

Our Current HTML Form Setup This is an example of the HTML form we are currently using. <form id="demo-form" action="post-handler.php" method="POST"> <input type="text" name="name" value=" ...

I implemented a proxy in my project to handle cross-domain requests, however, the requested address changes when I make a

Unable to Cross Domains http://localhost:8080/api/login has to be redirected to http://localhost:8080/index.html proxyTable: { '/api': { target: 'http://47.106.74.67:8080', changeOrigin: true, pathRewrite: ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...

What is the process for sending a complicated object to an MVC 4 controller using Ajax?

I am working with two objects in my project. The first one is DrawDie which has properties like ID, PlantID, QtyOnHand, SizeUS, SizeMetric, CaseSize, and Style. The second object is called DieOrder, which has properties such as ID, DrawDie (reference to a ...

My type is slipping away with Typescript and text conversion to lowercase

Here is a simplified version of the issue I'm facing: const demo = { aaa: 'aaa', bbb: 'bbb', } const input = 'AAA' console.log(demo[input.toLowerCase()]) Playground While plain JS works fine by converting &apo ...

The header row in HTML tables sometimes vanishes unexpectedly after sorting the table

Upon filtering the table, I noticed that the header disappears sporadically. The issue is that the table header row should remain in place regardless of whether or not the characters used for filtering are present in the table rows. In Example 1: When fil ...

A guide on utilizing webpack devServer proxy within a create react app

Currently, I am in the process of developing a new application with create-react-app and I am looking to incorporate some proxies into my code. In the past, I utilized webpack's devServer for this purpose. module.exports = { ... devServer: { ...

Determine the total number of nested objects within a JSON structure using Javascript

Consider the JSON structure below: { "id": "foo", "list": [ { "id": "A", "list": [ { "id": "B", "list": [ { "id": "C", "list": [ { ...

The attempt to connect with react-native-fetch-blob has not been successful

How do I resolve the issue of displaying a PDF from my assets folder in an Expo, React Native project using react-native-pdf? While scanning folders for symlinks, encountered an error with RNFetchBlob library in my project directory. The automatic linki ...

Javascript conditional testing

I need help coding a <div> to display only if the numeric input is 18 or above and the YO option is chosen. Any guidance on this would be highly appreciated. See the code snippet below. <input type=numeric id=ageSelf ng-model="ageSelf" style="c ...

Updating items within a nested list in Redux can be achieved by carefully managing the state and implementing actions to add or remove

My current state is set up like this: Fruits: { 34: { FruitsID: 34, FruitsList:{apple, pineapple, banana} } } I want to update my fruit list by adding 'peach' and 'pear', while also removing 'apple&apos ...

When attempting to send data from Ajax to PHP as JSON, an error occurs and the data transmission fails

When attempting to send data as JSON, an error response is received stating: SyntaxError: Unexpected token < in JSON at position 0. If the data is sent as text, it successfully reaches PHP, but PHP does not respond accordingly. AJAX/JavaScript using J ...

Export all entries without taking into account pagination limits

My current setup involves using Datatables with pagination. I recently integrated the Datatable.buttons library to enable an Export to Excel feature. However, I encountered a limitation where only the first 10 rows on the current page are exported due to p ...

combining the package.json files of the client and server into a single file

I need assistance with merging server-side code (in nodejs) and client-side code (with react) into a single package.json file. The server file is located in the project root directory, while the client-side code resides in the /client folder along with oth ...