What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code?

Snippet of Code:

if (null != data && data) {
  
data = data.map((item) => {
   const value = item.deadlineEntityList;
      delete item.deadlineEntityList;
        const deadlines = [];
            for (const deadlineEntity of value) { // This is where the Error occurs
              deadlines.push({
                deadlineId: deadlineEntity.deadlineId,
                period: deadlineEntity.deadlinePeriod,
                value: deadlineEntity.value
              });
            }
            return {...item, ...{ deadlines }};
          });

          const rows = [];
          const salesAreaNames = _.uniq(data.map((d) => d.kagName)) as string[];
          for (const n of salesAreaNames) {
            const salesAreaData = data.find((d) => d.kagName === n);
            if (salesAreaData && salesAreaData !== null) {
              const row: any = { kagName: salesAreaData.kagName, values: {}, mandantKagId: salesAreaData.mandantKagId };
              for (const deadline of salesAreaData.deadlines) {
                row.values[deadline.period.toLowerCase()] = this.transformAmount(deadline.value);
              }
              rows.push(row);
            }
          }
          this.data = rows;
        }

Answer №1

You've got this:

 for (const taskEntity of (data ?? [])) { // This is where the magic happens

This simple trick will ensure that any potential errors are avoided, as it will iterate through an empty array if the data variable is undefined or null.

Answer №2

Here is an example of how you could approach this problem:


const information = [];

if (null != information && information) {
  information = information.map((element) => {
    let { detailsList, ...itemWithoutDetailsList } = element;

    detailsList = detailsList || [];

    const details = detailsList.map((detailsEntity) => {
      return {
        detailId: detailsEntity.detailId,
        type: detailsEntity.detailType,
        info: detailsEntity.info,
      };
    });
    return { ...itemWithoutDetailsList, details };
  });

  const rows = [];
  const categories = _.uniq(information.map((i) => i.categoryName)) as string[];

  categories.forEach((category) => {
    const categoryData = information.find((i) => i.categoryName === category);
    const row = {
      categoryName: categoryData.categoryName,
      values: {},
      categoryId: categoryData.categoryId,
    };

    categoryData.details.forEach((detail) => {
      row.values[detail.type.toLowerCase()] = this.formatInformation(
        detail.info,
      );
    });

    rows.push(row);
  });

  this.informationData = rows;
}

To improve code readability, consider using tools like Prettier for formatting.

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

What are the consequences of relying too heavily on deep type inference in React and Typescript?

In the process of migrating my React + Javascript project to Typescript, I am faced with preserving a nice unidirectional flow in my existing code. The current flow is structured as follows: 1. Component: FoobarListComponent -> useQueryFetchFoobars() 2 ...

I recently updated Angular Cli and now my app is searching for node_modules in a different location. Is there a way for me to revert it

Current Versions. @angular/cli: 1.4.2 node: 6.10.0 os: linux x64 @angular/animations: 4.3.6 @angular/common: 4.3.6 @angular/compiler: 4.3.6 @angular/compiler-cli: 4.3.6 @angular/core: 4.3.6 @angular/forms: 4.3.6 @angular/http: 4.3.6 @angular/platform-brow ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

Combine all TypeScript enums into a single one

Looking for a way to combine two separate enums into one for easier use. export enum ActionTypes1 { ClearError = 'CLEAR_ERROR', PrependError = 'PREPEND_ERROR', } export enum ActionTypes2 { IncrementCounter = 'INCREMENT_COUNT ...

What is the best way to halt the current event handler thread's execution when another event is triggered that calls the same handler at

One of the functions in my code filters and sorts contents of a select dropdown based on input text entered by the user. The function filterSort() is triggered on each keyup event from the input field. Code $(inputTextField).keyup(function() { / ...

What are the steps for encoding a value using jquery serialize?

I attempted to encode all values using the following code: encodeURIComponent($("#customer_details").serialize()); Unfortunately, it did not produce the desired results. Is there a method to retrieve all elements on a form and individually encode each v ...

What is the best way to bypass using an if/else statement in TypeScript when dealing with mocha and returning undefined values

A unique spline able to be intertwined and produce a new version of itself, most of the time. export default class UniqueSpline { public intertwinedCount: number; constructor(parent?: UniqueSpline) { this.intertwinedCount = parent && pare ...

Definition file for Typescript Angular 1.5 component

Encountering a problem with typescript and angular 1.5 - when building, an error pops up saying error TS2339: Property 'component' does not exist on type 'IModule'.. Could it be that I overlooked a definition file containing this proper ...

"Exploring the insertion of a line break within the modal body of an Angular application

Is it possible to create a modal for error messages with multilined body messages without altering the modal template? Any assistance would be greatly appreciated. <div class="modal-body" > <p *ngIf="!_isTranslatable">{{_modalBody}}</p&g ...

The jQuery mouseout functionality seems to be malfunctioning and not responding as expected

I am currently developing a slider that displays details when the mouse hovers over the logo, and hides the details when the mouse moves away from the parent div. jQuery('.st_inner img').mouseover(function() { jQuery(this).parent().siblings( ...

Error in Node.js: The res.send method is undefined

I'm having some issues with my first attempt at creating a simple Counter Strike API bot using nodeJS. The problem lies with the res.send function, as I keep getting an error message saying "res.send is not a function" every time I try to use it. Movi ...

Activate a CSS class on click using JavaScript

Having a bit of trouble as a beginner with this. Any help would be much appreciated. This is the code in question: HTML: <div class='zone11'> <div class='book11'> <div class='cover11'></d ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

What is the process for modifying the user agent?

I'm struggling with phantom, the node.js wrapper for phantomjs. This is the approach needed in native phantomjs. page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/5 ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

Ways to update a component from another in React

My React code includes an Employees page that renders both a Table component and a Filter component. The Filter component manipulates some data stored in the Employees page, updates the Filter's state through useEffect, and passes the data as a prop t ...

Retrieve the PDF document from the AJAX call and save it as a

My goal is to have the browser automatically download a PDF file that is received from an AJAX response. After reading about how to download a PDF file using jQuery AJAX, I attempted to simulate a click/download event in this way: var req = new XMLHt ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...