2

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.

6
  • Use object.keys(arr2[i]) to get the header text of the inner objects - same them out to varaibles or to an array that can be used to give the th header text. Commented Jun 13, 2019 at 3:23
  • A better way to construct the table would be to use Node elements instead of treating the HTML as plain strings. This allows you to do things like insert nodes into other nodes by appending or prepending. Commented Jun 13, 2019 at 3:25
  • I'm still a javascript noob, so idk whether i should advance to learning node and all that :(. I would like to work on some basic javascript stuffs before I move on to learn more advanced libraries. Commented Jun 13, 2019 at 3:28
  • 1
    @djfdev is referring to DOM Nodes, not node.js. I strongly agree with him; if you want to learn JS, drop the reliance on jQuery and get to know the DOM all by yourself. Commented Jun 13, 2019 at 3:40
  • Yes, as @BlueWater86 said I was referring to DOM nodes. That being said, you could certainly do the same thing with jQuery selectors ... it’s really just a matter of thinking of the DOM as a tree structure rather than as a large concatenated string. Commented Jun 13, 2019 at 3:42

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

This answer +1. I honestly had no idea this API even existed until now. Blaming that on my heavy use of React throughout my frontend work haha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.