Home > Enterprise >  How to populate a Bootstrap table using selected elements of an array of objects using pure JavaScri
How to populate a Bootstrap table using selected elements of an array of objects using pure JavaScri

Time:09-16

I'd like to to populate a Bootstrap table from an array of objects using pure JavaScript.

Here is my data.js file:

JavaScript

let testData = [

    {
        id : 1,
        firstName : 'John',
        lastName : 'Smith',
        age :  35,
        retired : false
    },

    {
        id : 2,
        firstName : 'Mary',
        lastName : 'Williams',
        age :  27,
        retired : false
    },

    {   
        id : 3,
        firstName : 'Bill',
        lastName : 'Jones',
        age :  83,
        retired : true
    },

    {
        id : 4,
        firstName : 'Sally',
        lastName : 'Lee',
        age :  49,
        retired : false
    }
]

In my main.js file, I have the following function that builds the HTML and populates the table with only the firstName, lastName, and age. But, this function is not working.

function createTable(data) {
    var tr;
    for (var i = 0; i < data.length; i  ) {
        tr = $('<tr/>');
        tr.append("<td>"   data[i].firstName   "</td>");
        tr.append("<td>"   data[i].lastName   "</td>");
        tr.append("<td>"   data[i].age   "</td>");     
    }end(tr);
    }

createTable(testData)

Here is my index.html file:

HTML

<!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>Document</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">

</head>
<body>
     <div id="content-1"></div>

    <table >
        <thead>
          <tr>
            <th scope="col">First Name</th>
            <th scope="col">Last Name</th>
            <th scope="col">Age</th>
          </tr>
        </thead>
    </table>    

    <tbody>
        <!-- what goes here? -->

    </tbody>


    <script src="./js/data.js"></script>
    <script src="./js/main.js"></script>
</body>
</html>

Any assistance would be most appreciated!

Thanks!

CodePudding user response:

  1. tbody should be inside table element.
  2. You created the tr element correctly, but you didn't append it to the tbody.

const testData = [

    {
        id : 1,
        firstName : 'John',
        lastName : 'Smith',
        age :  35,
        retired : false
    },

    {
        id : 2,
        firstName : 'Mary',
        lastName : 'Williams',
        age :  27,
        retired : false
    },

    {   
        id : 3,
        firstName : 'Bill',
        lastName : 'Jones',
        age :  83,
        retired : true
    },

    {
        id : 4,
        firstName : 'Sally',
        lastName : 'Lee',
        age :  49,
        retired : false
    }
]

function createTable(data) {
    
    for (let i = 0; i < data.length; i  ) {
        let tr = $('<tr/>');
        tr.append("<td>"   data[i].firstName   "</td>");
        tr.append("<td>"   data[i].lastName   "</td>");
        tr.append("<td>"   data[i].age   "</td>");
        $('tbody').append(tr)
    }
}

createTable(testData)
<!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>Document</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>
     <div id="content-1"></div>

    <table >
        <thead>
          <tr>
            <th scope="col">First Name</th>
            <th scope="col">Last Name</th>
            <th scope="col">Age</th>
          </tr>
        </thead>
        <tbody>
        <!-- what goes here? -->

        </tbody>
    </table>    

</body>
</html>

With pure javascript ( without jquery )

const testData = [

    {
        id : 1,
        firstName : 'John',
        lastName : 'Smith',
        age :  35,
        retired : false
    },

    {
        id : 2,
        firstName : 'Mary',
        lastName : 'Williams',
        age :  27,
        retired : false
    },

    {   
        id : 3,
        firstName : 'Bill',
        lastName : 'Jones',
        age :  83,
        retired : true
    },

    {
        id : 4,
        firstName : 'Sally',
        lastName : 'Lee',
        age :  49,
        retired : false
    }
]

const tableBody = document.querySelector('tbody');

function createTable(data) {
    
    for (let i = 0; i < data.length; i  ) {
        let tr = document.createElement('tr');
        tr.innerHTML = `<td>${data[i].firstName}</td>
        <td>${data[i].lastName}</td>
        <td>${data[i].age}</td>`
        tableBody.append(tr)
    }
}

createTable(testData)
<!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>Document</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">
   

</head>
<body>
     <div id="content-1"></div>

    <table >
        <thead>
          <tr>
            <th scope="col">First Name</th>
            <th scope="col">Last Name</th>
            <th scope="col">Age</th>
          </tr>
        </thead>
        <tbody>
        <!-- what goes here? -->

        </tbody>
    </table>    

</body>
</html>

CodePudding user response:

I have added a fiddle link with the requested output. If my understanding isn't wrong, you have data in .js file as an array of objects and you need to populate the data in bootstrap table. Hopefully it helps!

HTML

<link href="https://unpkg.com/[email protected]/dist/bootstrap-table.min.css" rel="stylesheet">

<script src="https://unpkg.com/[email protected]/dist/bootstrap-table.min.js"></script>

<table id="table">
  <thead>
    <tr>
      <th data-field="id">Id</th>
      <th data-field="firstName">First Name</th>
      <th data-field="lastName">Last Name</th>
      <th data-field="age">Age</th>
      <th data-field="retired">Retired</th>
    </tr>
  </thead>
</table>

JS

var $table = $("#table");
    
    $(function () {
      let testData = [
        {
          id: 1,
          firstName: "John",
          lastName: "Smith",
          age: 35,
          retired: false,
        },
    
        {
          id: 2,
          firstName: "Mary",
          lastName: "Williams",
          age: 27,
          retired: false,
        },
    
        {
          id: 3,
          firstName: "Bill",
          lastName: "Jones",
          age: 83,
          retired: true,
        },
    
        {
          id: 4,
          firstName: "Sally",
          lastName: "Lee",
          age: 49,
          retired: false,
        },
      ];
      var data = [];
    
      testData.forEach(function (value) {
        data.push(value);
      });
      $table.bootstrapTable({ data: data });
    });

fiddle: http://jsfiddle.net/uvbqt6gc/

CodePudding user response:

<tbody> must always be located before <tfoot> or as the last child of a <table>. If a <tbody> is not added in HTML, it is added to each <table> by the browser by default.

Details are commented in example

const data = [{
  id: 1,
  firstName: 'John',
  lastName: 'Smith',
  age: 35,
  retired: false
}, {
  id: 2,
  firstName: 'Mary',
  lastName: 'Williams',
  age: 27,
  retired: false
}, {
  id: 3,
  firstName: 'Bill',
  lastName: 'Jones',
  age: 83,
  retired: true
}, {
  id: 4,
  firstName: 'Sally',
  lastName: 'Lee',
  age: 49,
  retired: false
}];

// Reference <tbody>
const tB = document.querySelector("table").tBodies[0];

/**
 * @desc - Generates table rows from data. A <table> must be in DOM.
 * @param {object<DOM>}   tbody   - Reference to a <table> or <tbody>
 * @param {array<object>} array   - An array of objects
 * @param {number<rest>}  headers - One or more numbers representing the
 *        index numbers of the first object of the array's keys. If 
 *        undefined it @default to all of the keys.
 */
function createRows(tbody, array, ...headers) {
  /**
   * Make an array of keys from the first object
   * ["id", "firstName", "lastName", "age", "retired"]
   */
  const keys = Object.keys(array[0]); 
  let hdrs;
  /**
    * If >...headers< is undefined, then >hdrs< is keys unfiltered
    * Otherwise >hdrs< is filtered by the index numbers of >...headers<
    * [...headers] = [1, 2, 3] 
    * hdrs = ["firstName", "lastName", "age"]
    */
  if ([...headers].length < 1) {
    hdrs = keys;
  } else {
    hdrs = keys.filter((_, i) => [...headers].includes(i));
  }
  /**
   * Add a <tr> for each object in the array
   * Add a <td> for each key of >hdrs<
   * Add the value that corresponds to each key of >hdrs< to each <td>
   */
  array.forEach(obj => {
    let tr = tbody.insertRow();
    hdrs.forEach(key => tr.insertCell().textContent = obj[key]);
  });
}

createRows(tB, data, 1, 2, 3);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
  <main >
    <section >
      <table >
        <thead>
          <tr>
            <th scope="col">First Name</th>
            <th scope="col">Last Name</th>
            <th scope="col">Age</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </section>
  </main>
</body>

</html>

  • Related