Min UD
Min UD

Reputation: 99

Creating a table from iterating through an array of objects

I have two types of arrays,

var arr1 = ["mike", "john"];
var arr2 = [{ 
    dan: {name: "dan brown", occupation: "police officer", age: 25},
    john: {name: "john blake", occupation: "student", age: 20},
    mike: {name: "mike floss", occupation: "student", age: 19}
    }];

I have displayed the tablebody using the following code.

function loopArray(arr1, arr2) {
    $.each(arr1, function(i) {
        var templateString = '<table id="partstable" class="table table-hover"><tbody><tr><td class="name">' 
        + arr2[arr1[i]].name + '</td><td>' 
        + arr2[arr1[i]].occupation + '</td><td>'
        + arr2[arr1[i]].age + '</td>';
        $('#test').append(templateString);
    })
}

and calling this function.

This is the output I have gotten.

This is the output I have gotten.

I would like to find out whether there is a way to add headers name, occupation and age to the table and whether there is a better way to output a table in general. Thank you for your help.

Upvotes: 2

Views: 1351

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30390

Another approach to dynamic table generation (without the need for jQuery) is via the Table Element API which you can use to construct a table dynamically from input data via it's object-orientated interface.

This API provides methods such as createTHead(), insertRow() on Table elements, and insertCell() on row elements which can be used as shown:

var arr1 = ["mike", "john"];
var arr2=[{dan:{name:"dan brown",occupation:"police officer",age:25},john:{name:"john blake",occupation:"student",age:20},mike:{name:"mike floss",occupation:"student",age:19}}];


/* Create table element */
const table = document.createElement('table');

/* Create header element and insert a row */
const header = table.createTHead().insertRow();

/* Populate table header with header cell labels */
header.insertCell(0).innerText = 'Name';
header.insertCell(1).innerText = 'Occupation';
header.insertCell(2).innerText = 'Age';

/* Create body element and insert to table */
const body = document.createElement('tbody');
table.appendChild(body);

arr1.forEach(person => {

  arr2.forEach(item => {

    const data = item[person];

    if (!data) {
      return;
    }

    /* If data present in arr2 for key person then 
    insert row into table body with corresponding 
    data entries */
    const row = body.insertRow();

    row.insertCell(0).innerText = data.name;
    row.insertCell(1).innerText = data.occupation;
    row.insertCell(2).innerText = data.age;
  });
});

/* Append table to test div */
document.getElementById('test').appendChild(table);
table thead {
  background:pink;
}

table td {
  padding:0.1rem;
}
<div id="test"></div>

Upvotes: 2

Related Questions