Search code examples
javascriptarraysjsoncodeigniterforeach

how to foreach array in array in javascript to table


i'm trying to foreach a punch of data to my table .. and the data comes from my controller (CI3) i try json encode like this:

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

and this is how i try to do foreach in my Javascript :

 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;

}

but i got this kind of error directly when i run it :

TypeError: data.forEach is not a function

and im not sure what is wrong in my code and i dont know how to fix it .

so can anyone tell me how to fix this one ?


Solution

  • The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

    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 table_show = (data) => {
        console.log(data)
        document.getElementById('mabody').innerHTML = '';
    
        let str_table = '';
     
        for (const [key, value] of Object.entries(data)) {
             console.log(`${key}: ${value}`);
             str_table += '<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>${str_table}</table>`;
        }
    
        window.addEventListener('load', (event) => {
            console.log('page is  loaded');
            table_show(data)
        });
       </script>
    </body>
    </html>