Creating a table from nested arrays in JavaScript using a foreach loop

Currently, I am attempting to loop through a set of data in order to populate my table. The data is being retrieved from my controller (CI3) and I have tried using JSON encoding like so:

{"1":{"2":["SOP","SOP 16","YES"]},"3":{"7":["SIP","SIP 12","YES"]},"4":{"18":["SAP","SAP 12","YES"]}}

This is the snippet of Javascript code where I attempted to loop through the data:

 const table_show = (data) => {
    console.log(data)
    document.getElementById('mabody').innerHTML = '';

    let str_table = '';
    data.forEach((ir_labs_1,key_ir_1) =>{
        str_table += '<tr id="data_ir_'+key_ir_1+'"><td>POSM</td><td>' + ir_labs_1 + '</td><td id="osa_'+key_ir_1+'">0</td></tr>';

    })
    document.getElementById('mabody').innerHTML = str_table;

}

However, upon running this code, I encounter the following error:

TypeError: data.forEach is not a function

I am uncertain as to what is causing this issue and how to resolve it. Can anyone provide guidance on how to rectify this problem?

Answer №1

The Object.entries() method is used to generate an array containing the key-value pairs of a specified object's properties that are enumerable.

Learn more about Object.entries()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <div id='mabody'></div>

    <script type="text/javascript">
    const data = {"1":{"2":["SOP","SOP 16","YES"]},"3":{"7":["SIP","SIP 12","YES"]},"4":{"18":["SAP","SAP 12","YES"]}}

    const displayTable = (data) => {
    console.log(data)
    document.getElementById('mabody').innerHTML = '';

    let tableContent = '';
 
    for (const [key, value] of Object.entries(data)) {
         console.log(`${key}: ${value}`);
         tableContent += '<tr id="data_ir_'+key+'"><td>POSM</td><td>' + JSON.stringify(value, null, 2) + '</td><td id="osa_'+key+'">0</td></tr>';
    }

    document.getElementById('mabody').innerHTML = `<table>${tableContent}</table>`;
    }

    window.addEventListener('load', (event) => {
        console.log('page is loaded');
        displayTable(data)
    });
   </script>
</body>
</html>

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

Error in AJAX transmission

I am encountering an unusual issue with the jQuery ajax function in my script. The problem is specific to my friend's computer, as I am not experiencing any difficulties on my own computer. While attempting to utilize the error function property to ...

Retrieve the original state of a ReactJs button from the database

I am completely new to ReactJs and I have a question regarding how to set the initial state of a button component based on data from an SQL database. I am successfully retrieving the data using PHP and JSON, but I am struggling with setting the state corre ...

Struggling to locate an element with jQuery's closest() method?

Currently, I am utilizing jQuery and Ruby on Rails for my project. Within a table with 3 columns, there is a form element in the form of a select box that utilizes AJAX to submit the result. My goal is to change the color of a check mark by adding or remov ...

Check if a given string conforms to the JSONATA expression format

Here's the scenario: A user inputs a JSONATA expression into a form field. The form should show an error message if the entered JSONATA expression is invalid. Is there a regular expression or pattern that can determine the validity of a string as a ...

Can you confirm if this is a valid JSONObject? If it is, could you please explain how I can iterate through it to access all

I received a valid JSON response from the server. {"Avg":[{"avg":3,"rcid":"ww44sd"},{"avg":4,"rcid":"ww24hj"},{"avg":3,"rcid":"ww36hd"},{"avg":4,"rcid":"ww89yx"},{"avg":3,"rcid":"ww64tf"},{"avg":4,"rcid":"ww76py"}]} Despite writing code that I believed w ...

What is the process for inputting data into a Inertia component?

I have a simple component: <script setup> import {ref} from 'vue' const labels = [] </script> <template> <div v-for="(label, index) in labels" :key="index" v-html="label"></div> </t ...

Using a dictionary to replace values in a Pandas DataFrame column with an array of new entries

I am working with a DataFrame that looks like this: tag1 other 0 a,c foo 1 b,c foo 2 d foo 3 a,a foo The entries in the DataFrame are strings separated by commas. In addition, I have a dictionary of definitions f ...

Combining PHP and SQL to group query results into an array

I am currently developing a website dedicated to property rentals. Let me provide some information regarding the relationships between the database objects and tables: In this setup, each property can consist of multiple units. For instance, a property l ...

Don't forget to save the toggleClass state to local storage in jQuery so it persists after

It's a challenge to maintain the value of toggleClass after refreshing or reloading the page. I have a structured table where rows toggle visibility when clicked. To preserve these toggle values, I utilized localStorage, but unfortunately, the state i ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

Having trouble with the dropdown feature on AngularJs?

Encountering an issue while trying to display the dropdown list. Upon inspecting in Chrome, it seems like the data is loading correctly but when clicked, the dropdown menu does not show up. The data is fetched from the BooksController and all options are ...

Tips for restricting camera movement in threejs

Being new to working with threejs, I am struggling to set limits on the camera position within my scene. When using OrbitControls, I noticed that there are no restrictions on how far I can zoom in or out, which I would like to change. Ideally, I want the c ...

Tips for extracting a specific field value from a JSON response

My current challenge involves calling an external API system from my website. When I receive the response in AJAX, it includes the following data. object(stdClass)#3 (3) { ["status"]=> string(7) "success" ["code"]=> int(200) ["data"]=> ...

Exceeded maximum file size event in Dropzone

I am currently implementing dropzone in my form to allow users to upload images. In the event that a user selects a file that exceeds the configured limit, I want to display an alert message and remove the file. Below is my current configuration: Dropzone ...

Guide on transforming data into the preferred format and saving it to a file using Python and Apache Beam

My dataset consists of a .ndjson file structured like this: {"property_id": "107", ...} {"property_id": "108", ...} {"property_id": "109", ...} Using Apache Beam, I grouped the data by property_i ...

Utilizing an array element within a conditional statement

I am currently working on an analysis to plot a series of values across a range of time values represented by the variable t in an array format. Ux and Uy are functions of t, as are U1, U2, Ep1, and Ep2, due to their relationships. The issue arises at the ...

Triggering functions when the mouse wheel is in motion

I am new to utilizing javascript and jquery, and my knowledge is limited at the moment. I am attempting to create a script that will trigger different functions based on the direction of mouse wheel movements in a way that works across various programs. Ca ...

The JSX snippet accurately displays the expected value on some pages, but displays an incorrect value on other pages

{_id === friendId || <IconButton onClick={() => patchFriend() } sx={{ backgroundColor: primaryLight, p: "0.6rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: primaryDark }} /> ...

Create a configuration featuring filter options similar to Notion's functionality

The objective is to create a system that can establish certain constraints, similar to the way Notion handles filter properties. https://i.sstatic.net/plctW.png System A sets up the constraints and System C evaluates them, both using Typescript. However, ...

Exporting a named export for every HTTP method is the way to go with NextJs

I'm currently working on a project to create an Airbnb clone using NextJs. The tutorial I'm following is using an experimental version, while I've opted for the latest version of NextJs. One aspect that's been causing confusion for me i ...