Create HTML table from JavaScript object

前端 未结 8 1107
后悔当初
后悔当初 2020-12-05 12:02

I am a beginner of JavaScript and want to display an array of objects in HTML.

The format of the data is like this:

[
  {\"key\":\"apple\",\"value\":         


        
相关标签:
8条回答
  • 2020-12-05 12:29

    Explanation

    What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.

    You want to loop through the object. The best way to do so would be with a for loop, and making sure our looping variable remains valid for the length of our object (all its attributes).

    The best way to get the length of a JSON object is through myJSONObject.length: You select the keys of myJSONObject and return their count.

    You can access the values stored in your JSON Object the following way, in your for loop (assuming the looping variable defined is named i): myJSONObject[i].theAttributeIWantToGet


    Price formatting breakdown

    Now, those prices need to have a proper format, don't they? So we'll check if any of the value attribute has less than 2 characters after the . within them. If they do, we add another decimal 0. We also add a $ before writing the formatted value. Here is a breakdown of how it works:

    • obj[i].value.toString().substring(startIndex, length)

      • We want to check the length after the . sign, so our startIndex will be the position of this dot within our string.
      • obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)
      • We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
      • Final result: obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2

        • This will return true or false. If it's true: There's less than 2 digits after the dot !
      • We add the if statement and the last zero:

      • if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0";

    Also: Why I use innerHTML instead of appendChild().


    Solution

    JSFiddle

    HTML

    <table>
        <tbody id="tbody"></tbody>
    </table>
    

    JSON

    [{
        "key": "apple",
        "value": 1.90
    }, {
        "key": "berry",
        "value": 1.7
    }, {
        "key": "banana",
        "value": 1.5
    }, {
        "key": "cherry",
        "value": 1.2
    }]
    

    JavaScript

    Note: The JSON object will be named obj in this instance.

    var tbody = document.getElementById('tbody');
    
    for (var i = 0; i < obj.length; i++) {
        var tr = "<tr>";
    
        /* Verification to add the last decimal 0 */
        if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) 
            obj[i].value += "0";
    
        /* Must not forget the $ sign */
        tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";
    
        /* We add the table row to the table body */
        tbody.innerHTML += tr;
    }
    

    JSFiddle

    0 讨论(0)
  • 2020-12-05 12:31

    Iterate through the list and retrieve the data for each item this way (assuming your data is in a var called data):

    for (var i = 0; i < data.length; i++) {
      var id = i + 1;
      var name = data[i].key;
      var relevance = data[i].value;
    }
    

    Then, do something with the variables in each loop, print them out however you want.

    0 讨论(0)
  • 2020-12-05 12:32

    Here a function for build a table from any collection (array of objects)

    Table creator

    const data=[
        {
            name: "Kapil",
            age:  21,
            status: "Active"
        },
        {
            name: "John",
            age:  28,
            status: "Inactive"
        },
        {
            name: "Deos",
            age:  18,
            status: "Active",
            testing: 'Gooo!!'
        }
    ]
    
    const createTable=function(data){
    const table = document.createElement("table");
    const header = document.createElement("tr");
    const keys=Object.keys(data[0])
    console.log(keys)
    for(const key of keys){
        const th=document.createElement("th");
        th.appendChild(document.createTextNode(key));
        header.appendChild(th);
    }
    table.appendChild(header);
    const len=data.length
    for(const row of data) {
        const tr = document.createElement("tr");
        for(const key of keys){
            const td = document.createElement("td");
            const content=row[key] ||''
            td.appendChild(document.createTextNode(content));
            tr.appendChild(td);
            delete row[key]
        }
      /****
      you can omit next cycle if all object have the same structor or if the first element of collection have all fields
      ****/
        for(const key in  row){
            const th=document.createElement("th");
            th.appendChild(document.createTextNode(key))
            keys.push(key)
            header.appendChild(th);
            const td = document.createElement("td");
            const content=row[key] ||''
            td.appendChild(document.createTextNode(content));
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    return table
    

    }

    0 讨论(0)
  • 2020-12-05 12:38

    Maybe like this:

    function obj2htmltable(obj) {
        var html = '<table>';
        for (var key in obj) {
            var value = obj[key].toString();
            html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
        }
        html += '</table>';
        return html;
    }
    

    If case of nested structure (objects inside object) obj2htmltable() could call itself recursively:

    function obj2htmltable(obj) {
        var html = '<table>';
        for (var key in obj) {
            var item = obj[key];
            var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString();
            html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
        }
        html += '</table>';
        return html;
    }
    
    0 讨论(0)
  • 2020-12-05 12:47

    Array.map() combined with template literals comes in really handy for rendering HTML markup within Javascript for large objects in a scalable manner:

    function tableMarkupFromObjectArray(obj) {
    
      let headers = `
      <th>Index</th>
      ${Object.keys(obj[0]).map((col) =>`
      <th>${col}</th>`
      ).join('')}`
    
      let content = obj.map((row, idx) => `
    <tr>
          <td>${idx}</td>
          ${Object.values(row).map((datum) => `
          <td>${datum}</td>`
        ).join('')}
        </tr>
    `).join('')
    
      let tablemarkup = `
      <table>
        ${headers}
        ${content}
      </table>
      `
      return tablemarkup
    }
    
    
    let myobj =[
      { "name": "apple", "rel": 1.90 },
      { "name": "berry", "rel": 1.7 },
      { "name": "banana", "rel": 1.5 },
      { "name": "cherry", "rel": 1.2 }
    ]
    
    document.querySelector("#mydiv").innerHTML = tableMarkupFromObjectArray(myobj)
    

    http://jsfiddle.net/4L7c5vad/

    0 讨论(0)
  • 2020-12-05 12:48

    You can do something like this:

    var table = document.createElement("table");
    
    //Add a header
    var header = document.createElement("tr");
    
    var idHeaderCell = document.createElement("th");
    var nameHeaderCell = document.createElement("th");
    var relevanceHeaderCell = document.createElement("th");
    
    header.appendChild(idHeaderCell);
    header.appendChild(nameHeaderCell);
    header.appendChild(relevanceHeaderCell);
    
    table.appendChild(header);
    
    //Add the rest of the data to the table
    for(var i = 0; i < data.length; i++) {
        var id = (i + 1);
        var name = data[i].key;
        var relevance = data[i].value;
    
        var tr = document.createElement("tr");
    
        var idCell = document.createElement("td");
        var nameCell = document.createElement("td");
        var relevanceCell = document.createElement("td");
    
        idCell.appendChild(document.createTextNode(id));
        nameCell.appendChild(document.createTextNode(name));
        relevanceCell.appendChild(document.createTextNode(relevance));
    
        tr.appendChild(idCell);
        tr.appendChild(nameCell);
        tr.appendChild(relevanceCell);
    
        table.appendChild(tr);
    }
    
    0 讨论(0)
提交回复
热议问题