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

The AngularJS array data is not displaying correctly

I am having trouble displaying comments array data in HTML properly. The data appears the same as it is in the comments array. What could be causing this issue? How should I proceed? <ul class="media-list" ng-controller="dishDetailController as menuCt ...

Merge two separate mongodb records

Just getting started with javascript / express / mongodb. For my initial project, I am working on a simple task manager where todos are categorized by priority - "high," "mid," or "low." However, I am facing an issue when trying to display different entri ...

Hover effect for changing image source not functioning as anticipated

I'm having issues creating an image that plays a GIF on hover. I came across some jQuery code on this website that should work, but it's not working for me. Any thoughts on what the problem might be? Here is the HTML and JavaScript code: $(doc ...

Customizing the appearance of several elements in CKEditor by applying inline styles

I am looking to apply inline styling to multiple HTML elements using the CKEditor's inline style option. In order to achieve this, I have included the following code snippet in the styles.js file: { name: 'Red italics', element: 'p&apo ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

ng2-auto-complete automatically selects default option on a reactive form

I'm currently integrating https://www.npmjs.com/package/ng2-auto-complete into my Angular 5 application and here's how my input is set up: HTML: <input id="shipper" type="text" class="form-control" for ...

Mastering the syntax of Babel in Node.js

Hey there! I've encountered a syntax issue while migrating to babel. The problem lies in importing an unnamed module. In traditional Node.js default import, it's possible to import without specifying the module name and passing in the app. Howeve ...

Attempting to configure Kafka consumer and producer components

Trying to establish a basic producer-consumer flow with Kafka, utilizing node-rdkafka Operating in debug: 'all' mode, the logs display: Producer: test [0]: MessageSet with 1 message(s) delivered Consumer: Fetch topic test [0] at offset 38 (v2) ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

Is there a way to capture the stdout and stderr output from a WebAssembly module that has been generated using Emscripten in JavaScript?

In my C++ code snippet below: #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } I compile the code using: emcc -s ENVIRONMENT=shell -s WASM=1 -s MODULARIZE=1 main.cpp -o main.js This c ...

Utilizing dynamic components in React JS

I'm a beginner in React JS and I'm facing an issue where I'm trying to call a React component from an HTML string that is being generated by another JavaScript class. However, the component is not rendering on the screen. class Form extends ...

Unexpected outcomes when trying to sort and paginate React-Table

Experiencing unexpected results with react-table integration for pagination and sorting. Merged examples from the react-table repository. Encountering an issue where table hooks reset the page index on re-render, causing fetchData to be called twice during ...

Utilizing variable index to access nested objects

When my Ajax request returns a response, the data takes the form of an object shown below: https://i.sstatic.net/wA2Px.png How can I access the value? Keep in mind that idVariable is a variable. data.test1.idVariable.test2.value The result of the code ...

"Use the data-attribute to dynamically append a child element to the

Here are a couple of divs that look like this: <div id="thisisme" data-order="1"> <div id="thisisme" data-order="2"> I am looking to insert some content into the specific div with data-order = 1. The following Javascript code is what I have t ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

Unable to interact with a button through JavaScript using execute_script in Selenium

https://i.stack.imgur.com/hJmtK.png I am attempting to remove a cookies popup by accepting the cookies and clicking confirm. While I am able to click an input labeled "zgadzam się na", for some reason, clicking a button with the label "potwierdź" appears ...

Caching of audio files in React streaming is enabled

My dilemma lies in the fact that despite creating a new file in the back-end, the <PlaySound /> component continues to play the old sound file rather than the updated one. Although the sound file maintains the same name and path, its content differs. ...

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 ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

JavaScript, specifically in the VueJS framework, consistently defaults to utilizing the final value within a

Describing my issue, I am using a for loop to extract elements from an array and assign them to a JSON value. It looks something like this: hotel={ rooms: 2, price: [ 100, 200 ], occupation: [ '1 child', '1 adult' ] I aim to push thi ...