Discovering the process of iterating through values from multiple arrays of objects and applying them to a new response in Angular 8

Received the following data from an API response:

const apiResponse = {
    "factoryId": "A_0421",
    "loss": [
        {
            "lossType": "Planned Stoppage Time",
            "duration": "1111"
        },
        {
            "lossType": "Quality Time",
            "duration": "2222"
        }
    ],
    "break": [
        {
            "lossType": "Format",
            "duration": "5.749999",
            "eventCount": "2"
        }
    ],
    "kpi": [
        {
            "mpl": "16556.598475000053"
        }
    ]
};

Looking for code to check if the API response contains arrays for loss, break, and kpi, and then extract and map values to form fields below.

I've attempted the code below but I'm struggling to access all array objects.

Could someone help me iterate through and patch all values in a more efficient manner?

prepareFormForImport(resp) {
      for (let element of resp) {
        return {
        factoryId: null,
          availableTime: {
            bankHoliday: element.loss.lossType === 'Bank Holidays' ? element.duration : 0,
            breakDownTime: element.loss.lossType === 'Quality Time' ? element.duration : 0
            },
            operatingTime: {
                maintenanceTime: element.break.lossType === 'Format' ? element.duration : 0
            },
            uom: element.kpi === 'mpl' ? element.mpl : 0
        }
    }
}

Answer №1

Could you attempt it in this manner?

  dataBundle: any[] = [
    {
      id: null,
      timeAvailability: {
        holiday: null,
        breakdownTime: null,
      },
      operationHours: {
        maintenanceDuration: null,
      },
      unitOfMeasure: null,
    }
  ];

  constructor() { }

  ngOnInit(): void {
    // Emulate the API response
    const apiData = {
      id: "A_0421",
      downtime: [
        {
          type: "Scheduled Downtime",
          duration: "1111"
        },
        {
          type: "Quality Control Time",
          duration: "2222"
        }
      ],
      stops: [
        {
          type: "Format Changeover",
          duration: "5.749999",
          frequency: "2"
        }
      ],
      performanceIndicators: [
        {
          mpl: "16556.598475000053"
        }
      ]
    };

    // Match the data from the API response to dataBundle
    this.transferData(apiData);
  }

  private transferData(apiData: any): void {
    if (apiData.downtime && Array.isArray(apiData.downtime)) {
      apiData.downtime.forEach((item: any) => {
        switch (item.type) {
          case "Scheduled Downtime":
            this.dataBundle[0].timeAvailability.holiday = item.duration;
            break;
          case "Quality Control Time":
            this.dataBundle[0].timeAvailability.breakdownTime = item.duration;
             break;
        }
      });
    }

    if (apiData.stops && Array.isArray(apiData.stops)) {
      apiData.stops.forEach((item: any) => {
        if (item.type === "Format Changeover") {
          this.dataBundle[0].operationHours.maintenanceDuration = item.duration;
        }
      });
    }

    if (apiData.performanceIndicators && Array.isArray(apiData.performanceIndicators)) {
      apiData.performanceIndicators.forEach((item: any) => {
        if (item.mpl) {
          this.dataBundle[0].unitOfMeasure = item.mpl;
        }
      });
    }
  }

Answer №2

This response addresses your query @Shilpa

//variables
let bankHoliday = '';
let breakDownTime = '';
let maintenanceTime = '';
let uom = '';

//Extract data from JSON using a function
function fetchData(data) {
  let object = JSON.parse(data);
  
  if(Object.hasOwn(object,'loss') && Object.hasOwn(object, 'break') && Object.hasOwn(object, 'kpi')) {
    object.loss.forEach((obj) => {
      if(obj.lossType === 'Bank Holidays') {
        bankHoliday = Number.parseFloat(obj.duration);
        }
      
      if(obj.lossType === 'Quality Time') {
        breakDownTime = Number.parseFloat(obj.duration);
        }
      });
    
    object.break.forEach((obj) => {
      if(obj.lossType === 'Format') {
        maintenanceTime = Number.parseFloat(obj.duration);
        }
      });
    
    object.kpi.forEach((obj) => {
      if(Object.hasOwn(obj, 'mpl')) {
        uom = Number.parseFloat(obj.mpl);
        }
      });
    
    
    }
   
  }

const apiResponse = '{"factoryId": "A_04","loss": [{"lossType": "Bank Holidays","duration": "1111"},{"lossType": "Quality Time","duration":"2222"}],"break": [{"lossType": "Format","duration": "5.749999","eventCount": "2"}],"kpi": [{"mpl": "16556.598475000053"}]}'
          
function processImportData(apiResponse) {
  fetchData(apiResponse);
  
  //Check if all variables have been populated
  if(bankHoliday !== '' && breakDownTime !== '' && maintenanceTime !== '' && uom !== '') {
    return {
      factoryId: null,
      availableTime: {
        bankHoliday: bankHoliday,
        breakDownTime: breakDownTime,
      },
      operatingTime: {
        maintenanceTime: maintenanceTime,
      },
      uom: uom,
    }
  }
}

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

Use the on-screen keyboard to move around by using the arrow keys and choose a value from the list to

I am currently working on developing an on-screen keyboard that allows for navigation using arrow keys and selection with the enter key. My goal is to have each selected key append to an input field. Below is the HTML code I have implemented: <div id ...

What is the reason behind the widespread adoption of Node.js and NPM for the compilation of JavaScript libraries by

The widespread adoption of Node.js and NPM in the JavaScript community has left me perplexed. Why must we rely on such drastic measures? What issues are these tools aiming to resolve for us? [Update] I feel like my original question missed the mark. Fra ...

Reorganizing JSON structures by incorporating unique identifiers into nested elements

I am working on restructuring an incoming JSON object to utilize in a React component. The JSON data that I'm receiving is stored in jsonData. This is the current structure of my code: const jsonData = { "Jonas": { "position": "CTO", "em ...

What is the best method to obtain access to the controls of an item within FormArray?

My goal is to assign an invalid class to the parent div of each input based on its validity status. In the form, I can control the input fields like this: <div class="form-group focus" [ngClass]="!recipeForm.controls.name.valid ? ...

Ways to verify the successful creation of a child process in NodeJS

I am attempting to use Node JS child_process to open a file as shown below var child_process =require('child_process'); var spawn = child_process.spawn; var exePath='<exe's path>' var filePath='<file path>' v ...

Guide on implementing factory updates to the display

I am attempting to update a reference within my factory in an asynchronous fashion, but I am not seeing the changes reflected in my view. View <div ng-repeat="Message in Current.Messages">{{Message.text}}</div> Controller angular.module(&ap ...

At that specific moment, a plugin is active to monitor the execution of JavaScript functions

Similar to how Fiddler allows you to monitor the communication between client and server, I am looking for a tool that can analyze all network traffic generated by client-side JavaScript on a webpage. Warm regards, bd ...

Different TypeScript parameters that cannot be used together

Consider the given JavaScript function below: function x({foo, fooId, bar, barId}) {} I am looking to refactor this function into TypeScript in such a way that the caller is required to provide either foo or fooId, but not both. The same rule should apply ...

Integrate a feature in your form that allows users to preview and edit their submission before finalizing

I've set up my HTML form with the following structure: <div class="container"> <div class="form-group" ng-controller="studentController"> <form role="form" class="well form-horizontal" id="registerForm" name="forms.register ...

Why is the value in my React Redux state not updating as expected?

I recently started learning react js as a beginner. To practice, I created a crud app and integrated firebase for authentication. However, I'm facing an issue where I'm not able to retrieve the updated value. Index.jsx At line 11, I'm stru ...

Here's how you can use welding techniques to attach objects and incorporate fin-like structures in THREE

I am currently working on a project involving a rocket ship orbiting various planets. To achieve this, I have started by creating my own rocket ship object and am aiming to model it similarly to this design: https://kyleagnew.files.wordpress.com/2018/02/lo ...

Managing User Sessions in Meteor

Is there a way to dynamically retrieve and set the pageTitle for my Meteor app using jQuery or any other method? I've attempted to achieve this by creating a session when a specific div class is present on the page, but it doesn't seem to be work ...

Tips for transferring data when clicking in Angular 5 from the parent component to the child component

I need assistance with passing data from a parent component to a child component in Angular 5. I want the child component to render as a separate page instead of within the parent's template. For example, let's say my child component is called & ...

The functionality of the Bootstrap collapse menu is not compatible with Angular

I'm experiencing difficulties with implementing the "collapse" effect in the menu using bootstrap and angular. I have set up the layout separately and everything seems to be functioning correctly, but as soon as I integrate angular, the menu stops wor ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

Deactivate a function within Bootstrap JavaScript

Is there a way to temporarily disable a function within Bootstrap after a click event? <a href="#"><span class="glyphicon glyphicon-triangle-right" id="btn04" onclick="myfun();"></span></a> Additionally, I am looking for a soluti ...

Adjusting elements within nested JavaScript arrays

When using the code below, an empty array containing 7 empty arrays is expected to be created, essentially forming a 7x7 grid. While accessing elements within nested arrays seems to work correctly, attempting to modify their values causes all elements in ...

Creating a compilation of material-ui using browserify

I am currently in the process of incorporating material-ui (material-ui.com) JavaScript into my project to utilize its React components. To streamline this process, I have been utilizing browserify to consolidate all the JavaScript files into a single one ...

imported classes from a module cannot be accessed within the same module

Here is some TypeScript code that I wrote: Within my module, I am importing a library called ts-events. import {SyncEvent} from 'ts-events' module MyModule{ export class MyService{ } } In the same module but in a different file, I'm ...