Manipulating an Array of Objects based on conditions in Angular 8

I have received an array of objects from an API response and I need to create a function that manipulates the data by enabling or disabling a flag based on certain conditions.

API Response

const data = [
      {
          "subfamily": "Hair Liquids (Includes: Bottles & Tottles, Tubes, Jars & Pouches)",
          "status": "New",
          "remainingTime": 6,
      },
      {
          "subfamily": "Skin Care - Liquids (Includes: Bottles & Tottles, Tubes, Jars & Pouches)",
          "status": "Submitted",
          "remainingTime": 6
      },
      {
          "subfamily": "Styling",
          "status": "New",
          "remainingTime": 6
      }
  ];

In order to determine whether the isButtonEnable flag should be enabled or disabled, we need to consider the following cases:

  1. If all object statuses are "New" and remainingTime is greater than 0, then set the isButtonEnable flag to True.
  2. If exactly 2 objects have a status of "Submitted" and one object has a status of "New" with remainingTime greater than 0, then set the isButtonEnable flag to True.
  3. If exactly 1 object has a status of "Submitted" and the other 2 objects have a status of "New" with remainingTime less than 0, then set the isButtonEnable flag to False.
  4. If exactly 1 object has a status of "Submitted" and the other 2 objects have a status of "New" with remainingTime greater than 0, then set the isButtonEnable flag to True.

I am looking for assistance in checking these conditions and updating the flags accordingly.

Below is the code snippet I have attempted:

enableFlagOnStatus(){
    if(data.length > 1){
      data.forEach((currentValue, index) => {
        if(currentValue.status === 'New' && remainingTime > 0){
          this.isButtonEnale = true;
        } else if(currentValue.status === 'Submitted' && remainingTime < 0){
          this.isButtonEnale = false;
        }        
      });
    }

  }

Answer №1

Give this a shot

function validateButton(data) {
    let newCount = 0;
    let submittedCount = 0;
    let isTimePositive = true;

    for (let item of data) {
        if (item.status === "New") {
            newCount++;
        } else if (item.status === "Submitted") {
            submittedCount++;
        }

        if (item.remainingTime <= 0) {
            isTimePositive = false;
        }
    }

    let isButtonEnabled = false;

    if (newCount === data.length && isTimePositive) {
        isButtonEnabled = true;
    } else if (submittedCount === 2 && newCount === 1 && isTimePositive) {
        isButtonEnabled = true;
    } else if (submittedCount === 1 && newCount === 2 && !isTimePositive) {
        isButtonEnabled = false;
    } else if (submittedCount === 1 && newCount === 2 && isTimePositive) {
        isButtonEnabled = true;
    }

    return isButtonEnabled;
}

Answer №2

Below is the code that meets your criteria.

enableFlagOnStatus() {
    if(data.length > 1){
        let newCount = 0;
        let submittedCount = 0;
        let remainingTime = 0;

        this.data.forEach((item) => {
            if (item.status === 'New') {
                newCount++;
            } else if (item.status === 'Submitted') {
                submittedCount++;
            }
            remainingTime = item.remainingTime;
        });

        if (newCount === 3 && remainingTime > 0) {
            this.isButtonEnabled = true;
        } else if (submittedCount >= 2 && newCount === 1 && remainingTime > 0) {
            this.isButtonEnabled = true;
        } else if (submittedCount === 1 && newCount === 2 && remainingTime < 0) {
            this.isButtonEnabled = false;
        } else if (submittedCount === 1 && newCount === 2 && remainingTime > 0) {
            this.isButtonEnabled = true;
        } else {
            this.isButtonEnabled = false;
        }
    }
}

Please make sure to correct the spelling of "isButtonEnale" to "isButtonEnabled".

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

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

Transferring selected radio button values to Javascript

This is an example of HTML code snippet: <tr> <td class="g"> Gender </td> <td class="g_input"> <input type="radio" name="gender" id="settings_gender" value="Male" checked />&nbsp;&nbsp;Male ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

Tips for retrieving the distance from the top of a specific div element and transferring it to another div

How can I add margin-top based on the tab that is clicked? Specifically, when TAB 4 is selected, I want the content to remain in the same position from the top. https://i.sstatic.net/ObDUg.jpg ...

There seems to be an issue with the Angular zone.js and zone-evergreen.js files showing an error that reads:

My Angular 11 app suddenly started showing errors across all browsers and environments (local, staging, prod) about an hour ago without any updates: Uncaught TypeError: t.getElementsByTagName is not a function at computeStackTrace.js:338 at Array.f ...

How can I incorporate Bootstrap multi-select into the jQuery DataTables DOM?

Having trouble implementing a bootstrap multi-select inside a jQuery datatable DOM. I followed this example to add a custom element within the jQuery datatable container. It works fine for normal bootstrap select, but when trying to add a bootstrap multi-s ...

Switch the view to a grid layout upon clicking

Using bootstrap 5, I've successfully created a list view: <div class="col"> Click to switch to grid/list </div> Below is the content list: <div class="row mt-3 list"> list view ... ..... ....... </div ...

Express router fails to mount

Struggling with my first project using expressjs, I have encountered an issue with a router not properly mounting. My approach involves the app mounting a router object which should then mount a second router object. While the first embedded router mounts ...

JavaScript - The AJAX response is consistently after being undefined

I am encountering an issue with the following functions: function get_non_authorized_bulk_edit_option_values() { var modificable_column_names = get_write_user_values(); alert(modificable_column_names); } The above function is calling this ...

Using AngularJS to create a form and showcase JSON information

My code is below: PizzaStore.html: <!DOCTYPE html> <html ng-app="PizzaApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Delicious pizza for all!</title> ...

Using NextJS to render a Link component by creating an element

Struggling to use createElement in NextJS to render a Link, but facing issues. Code: import {createElement} from "react"; import Link from "next/link"; createElement( item.href ? Link : "div", { href: item.hre ...

Transferring data from JavaScript variables to PHP function through AJAX requests

Within my dashboard.php, there is a JavaScript function triggered by a button click event named getTeamMembers. This function receives values from the user's interaction and passes them to a PHP function also present in dashboard.php. Despite my effo ...

Validate Bootstrap - Transmit data from all form fields to external PHP script

Is there a way to send all input field values to a remote PHP file using Bootstrap Validator? In my log in form, I have two input fields. I'm utilizing Bootstrap Validator's remote validation on both of them. However, each validation only sends ...

Transfer numerical values from PHP to JavaScript using individual files

What is the best way to pass variables from PHP to JavaScript when they are in separate files? Is it possible to achieve this without using AJAX, or is AJAX necessary for this task? If AJAX is required, how can I implement it? test.php <?php $a = 5; $ ...

In the Bootstrap multiselect feature, users will be able to choose whether to display an image or selected text

Is there any way to display an image by default instead of options? Code: <select id="example-post" style="width:120px;!important;" class="footerSelect" name="multiselect[]" multiple="multiple"> <opti ...

I am unable to retrieve values from the req.body object in Node.js

Can anyone assist with node.js? I am having trouble accessing the values in my req.body object. Here is how it is populated: { '{ "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670a060e0b270f0814130906 ...

Display a delete icon when hovering over a Chip component from Material-ui

Recently, I've been exploring ways to implement the on-hover functionality for a chip. What I'm looking for is when I hover over a chip in an array of chips, it should display a delete icon. Below is the code snippet I've been working on: ...

Numerous points highlighted on the map

As I develop my application, I am working on setting up an event to automatically load data from a CSV excel file for display. My goal is to extract information from the Excel CSV file and use it to populate locations on a Google Map within my application ...

Transmit information to a webpage using jQuery AJAX and the .data() function as you navigate to the page

<script> function sendUserData(username){ $.post("userprofile.php", { username:username } ); document.location.href="userprofile.php"; } $(document).on('click','#userprofile',function(){ var username=$(this).data('id4&apo ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...