XxnumbxX
XxnumbxX

Reputation: 134

How to create and populate multiple tables from multidimensional array using javascript

I am trying to create and populate multiple tables from a multidimensional array. My array is a multidimensional array that looks like below:

{
    "John Snow": [
        {
            "user_id": "4",
            "id": "28",
            "clock_in": "2019-06-03 14:32:14",
            "clock_out": "2019-06-04 14:32:14",
            "time": "24.00",
            "first_name": "John",
            "last_name": "Snow"
        },
        {
            "user_id": "4",
            "id": "29",
            "clock_in": "2019-06-04 20:47:18",
            "clock_out": "2019-06-05 18:47:18",
            "time": "22.00",
            "first_name": "John",
            "last_name": "Snow"
        }
    ],
    "Frank Thomas": [
        {
            "user_id": "6",
            "id": "30",
            "clock_in": "2019-06-03 06:32:04",
            "clock_out": "2019-06-05 14:05:04",
            "time": "55.55",
            "first_name": "Frank",
            "last_name": "Thomas"
        }
    ]
}

I am not sure how to loop through this with javascript, I'm guessing I will need to nest a for loop but not sure how to structure it.

I was able to loop through and populate a single table just fine when my array structure was a single array with no keys using the below code:

<div id="tables"></div>

<script type="text/javascript">


function search_data(){
            var fromDate = $('#from_date').val();
            var toDate = $('#to_date').val();
            var userId = $('#employee_option').val();


            $.ajax({

                url:"<?php echo base_url(); ?>clock/search_data",
                method:"post",
                dataType:"JSON",
                data:{fromDate:fromDate, toDate:toDate, userId:userId},
                success:function(data){
                    console.log(data)

                    var html = '<table class="table table-striped table-condensed table-responsive" id="myTable"><thead><tr><th>Employee</th><th>Time In</th><th>Time Out</th><th>Total Time</th><th>Action</th></tr></thead><tbody>';

                     for(var count = 0; count < data.length; count++){
                        html += '<tr>';
                        html += '<td class="table_data" data-row_id="'+data[count].id+'" data-column_name="id" >'+data[count].first_name+" "+data[count].last_name+'</td>';
                        html += '<td><input type="text" class="dateedit" data-row_id="'+data[count].id+'" data-column_name="clock_in" value="'+data[count].clock_in+'"></td>';
                        html += '<td><input type="text" class="dateedit" data-row_id="'+data[count].id+'" data-column_name="clock_out" value="'+data[count].clock_out+'"></td>';
                        html += '<td class="table_data" data-row_id="'+data[count].id+'" data-column_name="time">'+data[count].time+'</td>';
                        html += '<td><button type="button" name="delete_btn" id="'+data[count].id+'" class="btn btn-xs btn-danger btn_delete"><span class="glyphicon glyphicon-trash"></span></button></td></tr>';

                     }   

                     $('#tables').html(html);
                     $('.dateedit').each(function(){ 
                        $(this).datetimepicker({
                            format: "YYYY-MM-DD H:mm:ss",
                            sideBySide: true

                        });

                     });


                 }
                });

        }
        </script>

Any help would be appreciated, hopefully this makes sense. Here is a picture of what I have with a basic array: Need

Here is what I am trying to accomplish: Want

Upvotes: 0

Views: 1061

Answers (2)

Reed
Reed

Reputation: 14974

I would loop over the employees and pass them to another function to print out each employee... because I find nested loops hard to understand. easier to maintain & modify separate functions, IMO.

Note: I am a PHP dev who does minimal javascript, so don't expect my code to be up to snuff. I think this does what you want.

let employees = {
    "John Snow": [
        {
            "user_id": "4",
            "id": "28",
            "clock_in": "2019-06-03 14:32:14",
            "clock_out": "2019-06-04 14:32:14",
            "time": "24.00",
            "first_name": "John",
            "last_name": "Snow"
        },
        {
            "user_id": "4",
            "id": "29",
            "clock_in": "2019-06-04 20:47:18",
            "clock_out": "2019-06-05 18:47:18",
            "time": "22.00",
            "first_name": "John",
            "last_name": "Snow"
        }
    ],
    "Frank Thomas": [
        {
            "user_id": "6",
            "id": "30",
            "clock_in": "2019-06-03 06:32:04",
            "clock_out": "2019-06-05 14:05:04",
            "time": "55.55",
            "first_name": "Frank",
            "last_name": "Thomas"
        }
    ]
};

function get_employee_table(employeeName, employees){
	let str = "<table><tr><td>Employee Name</td><td>Clock In</td><td>Clock Out</td></tr>";
    for (let index in employees[employeeName]){
        let clock = employees[employeeName][index];
        str +="<tr><td>"+(clock['first_name']+" "+clock['last_name'])+"</td>"
            + "<td>"+clock['clock_in']+"</td>"
            + "<td>"+clock['clock_out']+"</td>"
            + "</tr>";
    }
    str +="</table>";
    return str;
}

for (let employee in employees){

    document.getElementById("employee_table_demo").innerHTML = document.getElementById("employee_table_demo").innerHTML + 
get_employee_table(employee,employees);
}
<div id="employee_table_demo"></div>

Now... here's where I share my opinion. I think you probably could have done this on your own. I had a hard time figuring out how to correctly loop over the objects, since the forin gave me the key, rather than the value. But the actual operation wasn't very complex. I realize we're all at different stages in our skill set, and if you're newer this could have seemed very perplexing. It seems like the kind of problem, though, that just required more elbow grease and maybe pushing through some frustration. T'was a nice learning experience for me though. And a good way to avoid working on my own projects lol.

Upvotes: 1

Siri
Siri

Reputation: 1126

Use a for..in loop to loop through the object and forEach through the array.

for(let row in data) {
  data[row].forEach(cell => {

  ...

  }
}

Upvotes: 0

Related Questions