简体   繁体   中英

How to add table row from array of objects in javascript?

How can we create table row using JavaScript

I was trying to create table row from array of objects in javascript using map function but somehow its throwing error

    const renderTableData = (result) => {
            return result.map((item, index) => {
                return (
                    <tr>
                        <td >item.Name</td>
                        <td >item.Date</td>
                        <td >item.state</td>
                    </tr>
                )
            })
        }


    const dataBinding = (result) => {
        let x = document.getElementById("tableSection");
        x.innerHTML = renderTableData(result);
    }

my html <table> <tbody id = "tableSection"> </tbody></table>

You should use a template string

 const renderTableData = (result) => { return result.map((item, index) => { return `<tr> <td >${item.Name}</td> <td >${item.Date}</td> <td >${item.state}</td> </tr>`; }).join(''); }; const dataBinding = (result) => { let x = document.getElementById("tableSection"); x.innerHTML = renderTableData(result); }; dataBinding([ { Name: "first", Date: "2020-09-21", state: "USA" }, { Name: "first", Date: "2020-09-21", state: "USA" }, { Name: "first", Date: "2020-09-21", state: "USA" }, ]);
 <table> <tr> <th>Name</th> <th>Date</th> <th>state</th> </tr> <tbody id="tableSection"></tbody> </table>

I used template string as we need to create for each item a multiline string. We could have achieved the same result with normal string but would have been much less readable.


             "<tr>\
                  <td >"+item.Name+"</td>\
                  <td >"+item.Date+"</td>\
                  <td >"+item.state+"</td>\
              </tr>"

After we map over the array of objects we end up with an array of strings. .join('') creates a single string out of that array and removes also the commas(if you set the innerHTML to an array, the commas between the elements will be considered as text to parse).

When you set the innerHTML of an element, the provided string is parsed as HTML. You can read more about it here

What you did on the first place was not valid javascript code, you were using a sort of JSX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM